﻿using JNPF.Basics.Logic.DataInterface;
using JNPF.Basics.Models;
using JNPF.Basics.Models.CodeBuilder;
using JNPF.Basics.Models.CodeBuilder.Template6;
using JNPF.Basics.Models.DataInterface.Entities;
using JNPF.Basics.Models.Enums;
using JNPF.Basics.Models.PlatForm.Dtos.VisualDev;
using JNPF.Basics.Models.Resx;
using JNPF.Basics.Models.VisualDev;
using JNPF.Basics.Models.VisualDevModelData;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using JNPF.Utils.Helper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 0代码功能数据表
    /// </summary>
    public class VisualDevModelDataService : DataFactory, VisualDevModelDataIService
    {
        private DictionaryDataService dictionaryService = new DictionaryDataService();
        private RedisHelper redisHelper = new RedisHelper();
        private DataInterfaceService dataInterfaceService = new DataInterfaceService();
        private OrganizeService organizeService = new OrganizeService();
        private PositionService positionService = new PositionService();
        private UserService userService = new UserService();
        private DictionaryTypeService dictionaryTypeService = new DictionaryTypeService();
        private ProvinceService provinceService = new ProvinceService();
        private BillRuleService billRuleService = new BillRuleService();
        private DbLinkIService dbLinkservice = new DbLinkService();
        private DatabaseIService databaseService = new DatabaseService();
        private VisualDevService visualDevService = new VisualDevService();

        /// <summary>
        /// 列表数据处理
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<Dictionary<string, object>>> GetListResult(VisualDevEntity entity, VisualDevModelListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var realList = new PageResult<Dictionary<string, object>>();
                realList.list = new List<Dictionary<string, object>>();
                var visualList = new List<VisualDevModelDataEntity>();
                List<VisualDevModelDataEntity> list = new List<VisualDevModelDataEntity>();
                Dictionary<string, object> columnData = TemplateKeywordsHelper.ReplaceKeywords(entity.ColumnData).ToObject<Dictionary<string, object>>();
                if (!string.IsNullOrEmpty(entity.Tables) && !"[]".Equals(entity.Tables))// 
                {
                    List<IndexGridFieldModel> modelList = columnData["columnList"].ToString().ToObject<List<IndexGridFieldModel>>();
                    List<TableModel> mapList = entity.Tables.ToString().ToObject<List<TableModel>>();
                    string mainTable = mapList.Find(m => m.relationTable == "").table;
                    var tableList = new List<DbTableFieldModel>();
                    tableList = databaseService.GetFieldListByNoAsync(null, mainTable);
                    var mainPrimary = tableList.Find(t => t.PrimaryKey == 1);
                    StringBuilder feilds = new StringBuilder();
                    modelList.ForEach(m =>
                    {
                        feilds.AppendFormat("{0},", m.prop);
                    });
                    if (modelList.Count > 0)
                    {
                        feilds = new StringBuilder(feilds.ToString().TrimEnd(','));
                    }
                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("select {0},{1} from {2}", mainPrimary.Field, feilds, mainTable);
                    if (!string.IsNullOrEmpty(columnData["defaultSidx"].ToString()))
                    {
                        input.sidx = columnData["defaultSidx"].ToString();
                        input.sord = columnData["sort"].ToString();
                    }
                    else
                    {
                        input.sord = columnData["sort"].ToString();
                    }
                    realList.list = await db.GetPageDictionaryAsync(sql.ToString());
                    list = GetTableDataList(realList.list);
                }
                else
                {

                    visualList = await GetList(entity.Id);
                    list = visualList;
                }
                //关键字过滤
                if (list.Count > 0)
                {
                    FormDataModel formDataModel = TemplateKeywordsHelper.ReplaceKeywords(entity.FormData).ToObject<FormDataModel>();
                    List<FieldsModel> formData = formDataModel.fields;
                    //剔除布局控件
                    formData = TemplateDataConversion(formData);
                    //获取模板数据缓存
                    Dictionary<string, object> templateData = await GetVisualDevTemplateData(entity.Id, formData);
                    //将查询的关键字json转成Dictionary
                    Dictionary<string, object> keyJsonMap = string.IsNullOrEmpty(input.json) ? null : input.json.ToString().ToObject<Dictionary<string, object>>();
                    //将关键字查询传输的id转换成名称
                    Dictionary<string, object> keyAndList = await GetKeyData(formData, templateData, keyJsonMap, list);
                    //关键字过滤
                    realList.list = GetRealList(keyAndList["keyJsonMap"].ToObject<Dictionary<string, object>>(), keyAndList["list"].ToObject<List<VisualDevModelDataEntity>>(), formData);
                }
                if (input.dataType == "0")
                {
                    realList.pagination = new PageOutput();
                    realList.pagination.total = realList.list.Count;
                    realList.pagination.pageSize = input.pageSize;
                    realList.pagination.currentPage = input.currentPage;
                    realList.list = realList.list.Skip(input.pageSize * (input.currentPage - 1)).Take(input.pageSize).ToList();
                    //分组表格
                    if (columnData["type"].ToString() == "3")
                    {
                        List<IndexGridFieldModel> modelList = columnData["columnList"].ToString().ToObject<List<IndexGridFieldModel>>();
                        var groupList = modelList.Where(p => p.prop == columnData["groupField"].ToString()).ToList();
                        var exceptList = modelList.Except(groupList).FirstOrDefault();
                        //分组数据
                        Dictionary<string, List<Dictionary<string, object>>> groupDic = new Dictionary<string, List<Dictionary<string, object>>>();
                        foreach (var item in realList.list)
                        {
                            var isExist = item.Select(p => p.Key == columnData["groupField"].ToString()).FirstOrDefault();
                            if (isExist)
                            {
                                var groupDicKey = item[columnData["groupField"].ToString()] is null ? "" : item[columnData["groupField"].ToString()].ToString();
                                if (!groupDic.ContainsKey(groupDicKey))
                                {
                                    groupDic.Add(groupDicKey, new List<Dictionary<string, object>>()); //初始化
                                }
                                item.Remove(columnData["groupField"].ToString());
                                groupDic[groupDicKey].Add(item);
                            }
                            else
                            {
                                var groupDicKey = "null";
                                if (!groupDic.ContainsKey(groupDicKey))
                                {
                                    groupDic.Add(groupDicKey, new List<Dictionary<string, object>>()); //初始化
                                }
                                groupDic[groupDicKey].Add(item);
                            }

                        }
                        List<Dictionary<string, object>> realGroupDic = new List<Dictionary<string, object>>();
                        foreach (var item in groupDic)
                        {
                            Dictionary<string, object> dataMap = new Dictionary<string, object>();
                            dataMap.Add("top", true);
                            dataMap.Add("children", item.Value);
                            dataMap.Add(exceptList.prop, item.Key);
                            realGroupDic.Add(dataMap);
                        }
                        realList.list = realGroupDic;
                    }
                }
                else
                {
                    realList.pagination = new PageOutput();
                    realList.pagination.total = realList.list.Count;
                    realList.pagination.pageSize = input.pageSize;
                    realList.pagination.currentPage = input.currentPage;
                    realList.list = realList.list.ToList();
                }

                return realList;
            }
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="modelId">模板ID</param>
        /// <returns></returns>
        public async Task<List<VisualDevModelDataEntity>> GetList(string modelId)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<VisualDevModelDataEntity>().And(m => m.VisualDevId == modelId);
                return await db.GetIQueryable<VisualDevModelDataEntity>().Where(queryWhere).OrderBy(o => o.SortCode).ToListAsync();
            }
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="modelId">模板ID</param>
        /// <param name="requestParam">分页参数</param>
        /// <returns></returns>
        public async Task<PageResult<VisualDevModelDataEntity>> GetList(string modelId, VisualDevModelListQueryInput requestParam)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<VisualDevModelDataEntity>().And(m => m.VisualDevId == modelId);
                var queryParam = requestParam.queryJson.ToObject();

                return await db.GetIQueryable<VisualDevModelDataEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(requestParam);
            }
        }

        /// <summary>
        /// 根据查询条件数据过滤数据
        /// </summary>
        /// <param name="keyJsonMap"></param>
        /// <param name="list"></param>
        /// <param name="timeControl"></param>
        /// <returns></returns>
        private List<Dictionary<string, object>> GetRealList(Dictionary<string, object> keyJsonMap, List<VisualDevModelDataEntity> list, List<FieldsModel> formData)
        {
            List<Dictionary<String, Object>> realList = new List<Dictionary<String, Object>>();
            foreach (var entity in list)
            {
                Dictionary<String, Object> query = keyJsonMap;
                Dictionary<String, Object> realEntity = entity.Data.ToObject<Dictionary<String, Object>>();
                if (query != null && query.Count != 0)
                {
                    //添加关键词全匹配计数，全符合条件则添加
                    int m = 0;
                    int dicCount = query.Keys.Count;
                    string[] strKey = new string[dicCount];
                    query.Keys.CopyTo(strKey, 0);
                    for (int i = 0; i < strKey.Length; i++)
                    {
                        var keyValue = keyJsonMap[strKey[i]];
                        var queryEntity = realEntity.Where(e => e.Key == strKey[i]).FirstOrDefault();
                        var model = formData.Where(f => f.__vModel__ == strKey[i]).FirstOrDefault();
                        if (queryEntity.Value != null && !string.IsNullOrWhiteSpace(keyValue.ToString()))
                        {
                            var realValue = queryEntity.Value;
                            var type = model.__config__.jnpfKey;
                            switch (type)
                            {
                                case JnpfKeyConsts.DATERANGE:
                                    {
                                        List<String> dayTime1 = keyValue.ToObject<List<string>>();
                                        List<String> dayTime2 = realValue.ToObject<List<string>>();
                                        var newList1 = new List<string> { dayTime1[0].TrimEnd('至') };
                                        var newList2 = new List<string> { dayTime2[0].TrimEnd('至') };
                                        dayTime1.RemoveRange(0, 1);
                                        dayTime2.RemoveRange(0, 1);
                                        dayTime1.InsertRange(0, newList1);
                                        dayTime2.InsertRange(0, newList2);
                                        bool cont1 = timeCalendar(dayTime2[0], dayTime1[0], dayTime1[1]);
                                        bool cont2 = timeCalendar(dayTime2[1], dayTime1[0], dayTime1[1]);
                                        if (cont1 || cont2)
                                        {
                                            realEntity["id"] = entity.Id;
                                            m++;
                                        }
                                    }
                                    break;
                                case JnpfKeyConsts.DATE:
                                    {
                                        if (realValue.ToString().Contains(keyValue.ToString()))
                                        {
                                            realEntity["id"] = entity.Id;
                                            m++;
                                        }
                                    }
                                    break;
                                case JnpfKeyConsts.TIMERANGE:
                                    {
                                        List<String> dayTime1 = keyValue.ToObject<List<string>>();
                                        List<String> dayTime2 = realValue.ToObject<List<string>>();
                                        if (dayTime2 != null)
                                        {
                                            var newList1 = new List<string> { dayTime1[0].TrimEnd('至') };
                                            var newList2 = new List<string> { dayTime2[0].TrimEnd('至') };
                                            dayTime1.RemoveRange(0, 1);
                                            dayTime2.RemoveRange(0, 1);
                                            dayTime1.InsertRange(0, newList1);
                                            dayTime2.InsertRange(0, newList2);
                                            bool cont1 = timeCalendar(dayTime2[0], dayTime1[0], dayTime1[1]);
                                            bool cont2 = timeCalendar(dayTime2[1], dayTime1[0], dayTime1[1]);
                                            if (cont1 || cont2)
                                            {
                                                realEntity["id"] = entity.Id;
                                                m++;
                                            }
                                        }
                                    }
                                    break;
                                default:
                                    {
                                        if (realValue.ToString().Contains(keyValue.ToString()))
                                        {
                                            realEntity["id"] = entity.Id;
                                            m++;
                                        }
                                    }
                                    break;
                            }
                        }
                        if (m == dicCount)
                        {
                            realList.Add(realEntity);
                        }
                    }
                }
                else
                {
                    realEntity["id"] = entity.Id;
                    realList.Add(realEntity);
                }
            }
            return realList;
        }

        /// <summary>
        /// 时间判断
        /// </summary>
        /// <param name="nowTime">数据时间</param>
        /// <param name="dayTimeStart">查询开始时间</param>
        /// <param name="dayTimeEnd">查询结束时间</param>
        /// <returns></returns>
        private bool timeCalendar(string nowTime, string dayTimeStart, string dayTimeEnd)
        {
            //设置当前时间
            DateTime date = DateTime.Parse(nowTime);
            //设置开始时间
            DateTime timeStart = DateTime.Parse(dayTimeStart);
            //设置结束时间
            DateTime timeEnd = DateTime.Parse(dayTimeEnd);
            //当date > timeStart时，date.CompareTo(timeStart)返回 1
            //当date = timeStart时，date.CompareTo(timeStart)返回 0
            //当date < timeStart时，date.CompareTo(timeStart)返回 -1
            if (DateTime.Compare(date, timeStart) >= 0 && DateTime.Compare(date, timeEnd) <= 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 将关键字key查询传输的id转换成名称，还有动态数据id成名称
        /// </summary>
        /// <param name="formData">数据库模板数据</param>
        /// <param name="templateData">模板真实数据</param>
        /// <param name="keyJsonMap">查询数据</param>
        /// <param name="list">真实数据</param>
        /// <returns></returns>
        public async Task<Dictionary<string, object>> GetKeyData(List<FieldsModel> formData, Dictionary<string, object> templateData, Dictionary<string, object> keyJsonMap, List<VisualDevModelDataEntity> list)
        {
            List<string> redisList = new List<string>();
            //转换列表数据
            foreach (var entity in list)
            {
                //数据库保存的F_Data
                Dictionary<string, object> dataMap = entity.Data.ToObject<Dictionary<string, object>>();
                int dicCount = dataMap.Keys.Count;
                string[] strKey = new string[dicCount];
                dataMap.Keys.CopyTo(strKey, 0);
                for (int i = 0; i < strKey.Length; i++)
                {
                    if (!(dataMap[strKey[i]] is null))
                    {
                        var form = formData.Where(f => f.__vModel__ == strKey[i]).FirstOrDefault();
                        if (form != null)
                        {
                            if (form.__vModel__.Contains(form.__config__.jnpfKey + "Field"))
                            {
                                dataMap[strKey[i]] = TemplateControlsDataConversion(dataMap[strKey[i]], form, "add");
                            }
                            else
                            {
                                dataMap[strKey[i]] = TemplateControlsDataConversion(dataMap[strKey[i]], form, "query");
                            }
                            var templateValue = templateData.Where(t => t.Key.Equals(strKey[i])).FirstOrDefault();
                            //转换后的数据值
                            var dataDicValue = dataMap[strKey[i]];
                            if (templateValue.Key != null && !(dataDicValue is null))
                            {
                                var jnpfKey = form.__config__.jnpfKey;
                                var moreValue = dataDicValue as IEnumerable<object>;
                                //不是List数据直接赋值
                                if (moreValue == null)
                                {
                                    jnpfKey = "";
                                }
                                switch (jnpfKey)
                                {
                                    case JnpfKeyConsts.COMSELECT:
                                        {
                                            StringBuilder addName = new StringBuilder();
                                            List<Dictionary<string, string>> dicAdd = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var comData = dicAdd.Where(a => a.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (comData != null)
                                                {
                                                    addName.Append(comData[item.ToString()] + ",");
                                                }
                                            }
                                            if (addName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = addName.ToString().TrimEnd(',');
                                            }
                                        }
                                        break;
                                    case JnpfKeyConsts.DEPSELECT:
                                        {
                                            StringBuilder addName = new StringBuilder();
                                            List<Dictionary<string, string>> dicAdd = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var comData = dicAdd.Where(a => a.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (comData != null)
                                                {
                                                    addName.Append(comData[item.ToString()] + ",");
                                                }
                                            }
                                            if (addName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = addName.ToString().TrimEnd(',');
                                            }
                                        }
                                        break;
                                    case JnpfKeyConsts.ADDRESS:
                                        {
                                            StringBuilder addName = new StringBuilder();
                                            List<Dictionary<string, string>> dicAdd = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var addressData = dicAdd.Where(a => a.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (addressData != null)
                                                {
                                                    addName.Append(addressData[item.ToString()] + "/");
                                                }
                                            }
                                            if (addName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = addName.ToString().TrimEnd('/');
                                            }
                                        }
                                        break;
                                    case JnpfKeyConsts.CASCADER:
                                        {
                                            StringBuilder addName = new StringBuilder();
                                            List<Dictionary<string, string>> dicAdd = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var cascaderData = dicAdd.Where(c => c.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (cascaderData != null)
                                                {
                                                    addName.Append(cascaderData[item.ToString()] + "/");
                                                }
                                            }
                                            if (addName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = addName.ToString().TrimEnd('/');
                                            }
                                        }
                                        break;
                                    case JnpfKeyConsts.CHECKBOX:
                                        {
                                            StringBuilder addName = new StringBuilder();
                                            List<Dictionary<string, string>> dicAdd = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var cascaderData = dicAdd.Where(c => c.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (cascaderData != null)
                                                {
                                                    addName.Append(cascaderData[item.ToString()] + ",");
                                                }
                                            }
                                            if (addName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = addName.ToString().TrimEnd(',');
                                            }
                                        }
                                        break;
                                    case JnpfKeyConsts.USERSELECT:
                                        {
                                            StringBuilder userName = new StringBuilder();
                                            List<Dictionary<string, string>> dicUser = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var cascaderData = dicUser.Where(c => c.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (cascaderData != null)
                                                {
                                                    userName.Append(cascaderData[item.ToString()] + ",");
                                                }
                                            }
                                            if (userName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = userName.ToString().TrimEnd(',');
                                            }
                                        }
                                        break;
                                    case JnpfKeyConsts.POSSELECT:
                                        {
                                            StringBuilder posName = new StringBuilder();
                                            List<Dictionary<string, string>> dicPos = templateValue.Value.ToJson().ToList<Dictionary<string, string>>();
                                            foreach (var item in moreValue)
                                            {
                                                var cascaderData = dicPos.Where(c => c.ContainsKey(item.ToString())).FirstOrDefault();
                                                if (cascaderData != null)
                                                {
                                                    posName.Append(cascaderData[item.ToString()] + ",");
                                                }
                                            }
                                            if (posName.Length != 0)
                                            {
                                                dataMap[strKey[i]] = posName.ToString().TrimEnd(',');
                                            }
                                        }
                                        break;
                                    default:
                                        {
                                            var convertList = templateValue.Value.ToObject<List<Dictionary<string, string>>>();
                                            var convertData = convertList.Where(t => t.ContainsKey(dataMap[strKey[i]].ToString())).FirstOrDefault();
                                            if (convertData != null)
                                            {
                                                dataMap[strKey[i]] = convertData.GetValue(dataMap[strKey[i]].ToString());
                                            }
                                        }
                                        break;
                                }
                            }
                        }
                    }
                }
                //转换模板没记录的数据
                var record = dataMap.Keys.Except(templateData.Keys).ToList();
                //针对有表的模板去除"rownum,F_Id"
                record.RemoveAll(r => { return r == "ROWNUM"; });
                record.RemoveAll(r => { return r == "F_Id"; });
                foreach (var key in record)
                {
                    if (!(dataMap[key] is null) && dataMap[key].ToString() != "")
                    {
                        var model = formData.Where(f => f.__vModel__ == key).FirstOrDefault();
                        if (model != null)
                        {
                            ConfigModel configModel = model.__config__;
                            string type = configModel.jnpfKey;
                            switch (type)
                            {
                                //switch开关
                                case "switch":
                                    {
                                        dataMap[key] = dataMap[key].ToInt() == 0 ? "关" : "开";
                                    }
                                    break;
                                //时间范围
                                case JnpfKeyConsts.TIMERANGE:
                                    {
                                        IEnumerable<object> dataList = dataMap[key] as IEnumerable<object>;
                                        List<string> jsonArray = new List<string>();
                                        if (dataList != null)
                                        {
                                            jsonArray = dataMap[key].ToObject<List<string>>();
                                        }
                                        else
                                        {
                                            jsonArray = dataMap[key].ToString().Split(',').ToObject<List<string>>();
                                        }
                                        string value1 = string.Format("{0:" + model.format + "}", jsonArray[0].Replace("[\r\n  ", ""));
                                        string value2 = string.Format("{0:" + model.format + "}", jsonArray[1].Replace("\r\n  ", "").Replace("\r\n]", ""));
                                        jsonArray.Clear();
                                        jsonArray.Add(value1 + "至");
                                        jsonArray.Add(value2);
                                        dataMap[key] = jsonArray;
                                    }
                                    break;
                                //日期选择
                                case JnpfKeyConsts.DATE:
                                    {
                                        string value = string.Empty;
                                        if (model.__vModel__.Contains(model.__config__.jnpfKey + "Field"))
                                        {
                                            value = string.Format("{0:" + model.format + "}", Convert.ToDateTime(dataMap[key].ToString()));
                                        }
                                        else
                                        {
                                            value = string.Format("{0:" + model.format + "}", CommonHelper.GetDateTime(dataMap[key].ToString()));
                                        }
                                        dataMap[key] = value;
                                    }
                                    break;
                                //日期选择
                                case JnpfKeyConsts.TIME:
                                    {
                                        string value = string.Empty;
                                        if (model.__vModel__.Contains(model.__config__.jnpfKey + "Field"))
                                        {
                                            value = string.Format("{0:" + model.format + "}", Convert.ToDateTime(dataMap[key].ToString()));
                                        }
                                        else
                                        {
                                            value = string.Format("{0:" + model.format + "}", dataMap[key].ToString());
                                        }
                                        dataMap[key] = value;
                                    }
                                    break;
                                //日期范围
                                case JnpfKeyConsts.DATERANGE:
                                    {
                                        IEnumerable<object> dataList = dataMap[key] as IEnumerable<object>;
                                        List<string> jsonArray = new List<string>();
                                        if (dataList != null)
                                        {
                                            jsonArray = dataMap[key].ToObject<List<string>>();
                                        }
                                        else
                                        {
                                            jsonArray = dataMap[key].ToString().Split(',').ToObject<List<string>>();
                                        }
                                        string value1 = string.Format("{0:" + model.format + "}", CommonHelper.GetDateTime(jsonArray[0].Replace("[\r\n  ", "")));
                                        string value2 = string.Format("{0:" + model.format + "}", CommonHelper.GetDateTime(jsonArray[1].Replace("\r\n  ", "").Replace("\r\n]", "")));
                                        jsonArray.Clear();
                                        jsonArray.Add(value1 + "至");
                                        jsonArray.Add(value2);
                                        dataMap[key] = jsonArray;
                                    }
                                    break;
                                case "currDept":
                                    {
                                        List<OrganizeEntity> orgMapList = await organizeService.GetList();
                                        foreach (var organizeEntity in orgMapList)
                                        {
                                            if (dataMap[key].ToString().Equals(organizeEntity.Id))
                                            {
                                                dataMap[key] = organizeEntity.FullName;
                                            }
                                        }
                                    }
                                    break;
                                case "createUser":
                                    {
                                        UserEntity userCreEntity = await userService.GetInfo(dataMap[key].ToString());
                                        if (userCreEntity != null)
                                        {
                                            dataMap[key] = userCreEntity.RealName;
                                        }
                                        else
                                        {
                                            dataMap[key] = dataMap[key];
                                        }
                                    }
                                    break;
                                case "createTime":
                                    {
                                        string value = string.Format("{0:yyyy-MM-dd HH:mm:ss}", Convert.ToDateTime(dataMap[key].ToString()));
                                        dataMap[key] = value;
                                    }
                                    break;
                                case "modifyUser":
                                    {
                                        UserEntity userModEntity = await userService.GetInfo(dataMap[key].ToString());
                                        if (userModEntity != null)
                                        {
                                            dataMap[key] = userModEntity.RealName;
                                        }
                                        else
                                        {
                                            dataMap[key] = dataMap[key];
                                        }
                                    }
                                    break;
                                case "modifyTime":
                                    {
                                        string value = string.Format("{0:yyyy-MM-dd HH:mm:ss}", Convert.ToDateTime(dataMap[key].ToString()));
                                        dataMap[key] = value;
                                    }
                                    break;
                                case "currPosition":
                                    {
                                        List<PositionEntity> mapList = await positionService.GetList();
                                        var position = mapList.Where(p => p.Id == dataMap[key].ToString()).FirstOrDefault();
                                        if (position != null)
                                        {
                                            dataMap[key] = position.FullName;
                                        }
                                    }
                                    break;
                                case "currOrganize":
                                    {
                                        List<OrganizeEntity> orgMapList = await organizeService.GetList();
                                        foreach (var organizeEntity in orgMapList)
                                        {
                                            if (dataMap[key].ToString().Equals(organizeEntity.Id))
                                            {
                                                dataMap[key] = organizeEntity.FullName;
                                            }
                                        }
                                    }
                                    break;
                                case "cascader":
                                    {
                                        switch (configModel.dataType)
                                        {
                                            case "dictionary":
                                                {
                                                    List<DictionaryDataEntity> data = new List<DictionaryDataEntity>();
                                                    if (redisHelper.Exists(CacheKey.VISUALDEV + configModel.dictionaryType))
                                                    {
                                                        data = redisHelper.Get(CacheKey.VISUALDEV + configModel.dictionaryType).ToObject<List<DictionaryDataEntity>>();
                                                    }
                                                    else
                                                    {
                                                        data = await dictionaryService.GetList(configModel.dictionaryType);
                                                        redisHelper.Insert(CacheKey.VISUALDEV + configModel.dictionaryType, data);
                                                        redisList.Add(CacheKey.VISUALDEV + configModel.dictionaryType);
                                                    }
                                                    List<string> dataList = dataMap[key].ToObject<List<string>>();
                                                    List<string> cascaderList = new List<string>();
                                                    foreach (var items in dataList)
                                                    {
                                                        var cascader = data.Find(d => d.Id == items);
                                                        if (cascader != null)
                                                        {
                                                            cascaderList.Add(cascader.FullName);
                                                        }
                                                    }
                                                    dataMap[key] = cascaderList;
                                                }
                                                break;
                                            case "dynamic":
                                                {
                                                    //获取远端数据
                                                    //DataInterfaceEntity dynamic = await dataInterfaceService.GetInfo(configModel.propsUrl);
                                                    //if (1.Equals(dynamic.DataType))
                                                    //{
                                                    //    var linkEntity = await dbLinkservice.GetInfo(dynamic.DBLinkId);
                                                    //    var dt = await databaseService.GetInterFaceData(linkEntity, dynamic.Query);
                                                    //    List<Dictionary<string, object>> dynamicDataList = UtilConvert.DataTableToDicList(dt);
                                                    //    List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                                    //    foreach (var item in dynamicDataList)
                                                    //    {
                                                    //        Dictionary<string, string> dynamicDic = new Dictionary<string, string>();
                                                    //        dynamicDic.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                                    //        list.Add(dynamicDic);
                                                    //    }
                                                    //    templateData.Add(fieldName1, list);
                                                    //}
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    break;
                                //关联表单
                                case JnpfKeyConsts.RELATIONFORM:
                                    {
                                        List<VisualDevFieldDataSelectOutput> relationFormDataList = new List<VisualDevFieldDataSelectOutput>();
                                        var redisName = CacheKey.VISUALDEV + configModel.jnpfKey + "_" + model.modelId;
                                        if (redisHelper.Exists(redisName))
                                        {
                                            relationFormDataList = redisHelper.Get(redisName).ToObject<List<VisualDevFieldDataSelectOutput>>();
                                        }
                                        else
                                        {
                                            //根据可视化功能ID获取该模板全部数据
                                            var relationFormModel = await visualDevService.GetInfo(model.modelId);
                                            FormDataModel relationFormData = relationFormModel.FormData.ToObject<FormDataModel>();
                                            //多虑多余控件
                                            var newFields = this.TemplateDataConversion(relationFormData.fields);
                                            var newFieLdsModelList = newFields.FindAll(x => model.relationField.Equals(x.__vModel__));
                                            VisualDevModelListQueryInput listQueryInput = new VisualDevModelListQueryInput
                                            {
                                                dataType = "1"
                                            };
                                            var relationFormList = (await this.GetListResult(relationFormModel, listQueryInput)).list;
                                            relationFormDataList = relationFormList.FindAll(x => x.ContainsKey(model.relationField)).Select(x => new VisualDevFieldDataSelectOutput()
                                            {
                                                id = x["id"].ToString(),
                                                fullName = x[model.relationField].IsEmpty() ? "" : x[model.relationField].ToString()
                                            }).ToList();
                                            redisHelper.Insert(redisName, relationFormDataList);
                                            redisList.Add(redisName);
                                        }
                                        var relationFormRealData = relationFormDataList.Find(r => r.id == dataMap[key].ToString());
                                        dataMap[key + "_id"] = relationFormRealData.id;
                                        dataMap[key] = relationFormRealData.fullName;
                                    }
                                    break;
                            }
                        }
                    }
                }
                //为数据实时性，接口请求完后删除Redis缓存
                if (redisList != null)
                {
                    foreach (var items in redisList)
                    {
                        redisHelper.Remove(items);
                    }
                }
                entity.Data = SerializeHelper.SerializeToString(dataMap);
            }
            //转换查询数据
            if (keyJsonMap != null)
            {
                int dicCount = keyJsonMap.Keys.Count;
                string[] strKey = new string[dicCount];
                keyJsonMap.Keys.CopyTo(strKey, 0);
                for (int i = 0; i < strKey.Length; i++)
                {
                    var value = keyJsonMap[strKey[i]];
                    //如果是多个值
                    if (value.ToString().Contains(',') && !value.ToString().Contains('['))
                    {
                        StringBuilder str = new StringBuilder();
                        string[] data = value.ToString().Split(',');
                        foreach (var item in data)
                        {
                            var template = templateData.Where(t => t.Key.Contains(strKey[i])).FirstOrDefault();
                            if (template.Key != null && !string.IsNullOrWhiteSpace(value.ToString()))
                            {
                                var convertList = template.Value.ToObject<List<Dictionary<string, string>>>();
                                var convertData = convertList.Where(t => t.ContainsKey(value.ToString())).FirstOrDefault();
                                if (convertData != null)
                                {
                                    str.AppendFormat("{0},", convertData.GetValue(item));
                                }
                            }
                        }
                        keyJsonMap[strKey[i]] = str.ToString().TrimEnd(',');
                    }
                    else if (value.ToString().Contains('['))
                    {
                        var moreJson = value.ToJson();
                        if (!moreJson.Equals("[{}]"))
                        {
                            var moreValue = moreJson.ToList<object>();
                            var form = formData.Where(f => f.__vModel__ == strKey[i]).FirstOrDefault();
                            var jnpfKey = form.__config__.jnpfKey;
                            switch (jnpfKey)
                            {
                                case JnpfKeyConsts.ADDRESS:
                                    {
                                        StringBuilder addName = new StringBuilder();
                                        var address = templateData.Where(t => t.Key.Equals(strKey[i])).FirstOrDefault();
                                        List<Dictionary<string, string>> dicAdd = address.Value.ToJson().ToList<Dictionary<string, string>>();
                                        foreach (var item in moreValue)
                                        {
                                            var addressData = dicAdd.Where(a => a.ContainsKey(item.ToString())).FirstOrDefault();
                                            if (addressData != null)
                                            {
                                                addName.Append(addressData[item.ToString()] + "/");
                                            }
                                        }
                                        if (addName.Length != 0)
                                        {
                                            keyJsonMap[strKey[i]] = addName.ToString().TrimEnd('/');
                                        }
                                    }
                                    break;
                                case JnpfKeyConsts.CASCADER:
                                    {
                                        StringBuilder addName = new StringBuilder();
                                        switch (form.__config__.dataType)
                                        {
                                            case "static":
                                                {
                                                    var cascader = templateData.Where(t => t.Key.Equals(strKey[i])).FirstOrDefault();
                                                    List<Dictionary<string, string>> dicAdd = cascader.Value.ToJson().ToList<Dictionary<string, string>>();
                                                    foreach (var item in moreValue)
                                                    {
                                                        var cascaderData = dicAdd.Where(c => c.ContainsKey(item.ToString())).FirstOrDefault();
                                                        if (cascaderData != null)
                                                        {
                                                            addName.Append(cascaderData[item.ToString()] + "/");
                                                        }
                                                    }
                                                    if (addName.Length != 0)
                                                    {
                                                        keyJsonMap[strKey[i]] = addName.ToString().TrimEnd('/');
                                                    }
                                                }
                                                break;
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    else
                    {
                        var template = templateData.Where(t => t.Key.Contains(strKey[i])).FirstOrDefault();
                        //找到模板数据
                        if (template.Key != null && !string.IsNullOrWhiteSpace(keyJsonMap[strKey[i]].ToString()))
                        {
                            var convertList = template.Value.ToObject<List<Dictionary<string, string>>>();
                            var convertData = convertList.Where(t => t.ContainsKey(keyJsonMap[strKey[i]].ToString())).FirstOrDefault();
                            if (convertData != null)
                            {
                                keyJsonMap[strKey[i]] = convertData.GetValue(keyJsonMap[strKey[i]].ToString());
                            }
                        }
                    }
                }
                //转换查询条件没记录的数据
                var record = keyJsonMap.Keys.Except(templateData.Keys).ToList();
                foreach (var key in record)
                {
                    var model = formData.Where(f => f.__vModel__ == key).FirstOrDefault();
                    ConfigModel configModel = model.__config__;
                    string type = configModel.jnpfKey;
                    switch (type)
                    {
                        //时间范围
                        case JnpfKeyConsts.TIMERANGE:
                            {
                                List<string> jsonArray = keyJsonMap[key].ToObject<List<string>>();
                                string value1 = string.Format("{0:HH:mm:ss}", jsonArray[0].ToDate());
                                string value2 = string.Format("{0:HH:mm:ss}", jsonArray[1].ToDate());
                                jsonArray.Clear();
                                jsonArray.Add(value1 + "至");
                                jsonArray.Add(value2);
                                keyJsonMap[key] = jsonArray;
                            }
                            break;
                        //日期选择
                        case JnpfKeyConsts.DATE:
                            {
                                string value = string.Format("{0:yyyy-MM-dd}", CommonHelper.GetDateTime(keyJsonMap[key].ToString()));
                                keyJsonMap[key] = value;
                            }
                            break;
                        //日期范围
                        case JnpfKeyConsts.DATERANGE:
                            {
                                List<string> jsonArray = keyJsonMap[key].ToObject<List<string>>();
                                string value1 = string.Format("{0:yyyy-MM-dd}", CommonHelper.GetDateTime(jsonArray[0]));
                                string value2 = string.Format("{0:yyyy-MM-dd}", CommonHelper.GetDateTime(jsonArray[1]));
                                jsonArray.Clear();
                                jsonArray.Add(value1 + "至");
                                jsonArray.Add(value2);
                                keyJsonMap[key] = jsonArray;
                            }
                            break;
                        case "createUser":
                            {
                                keyJsonMap[key] = keyJsonMap[key];
                            }
                            break;
                        case "createTime":
                            {
                                string value = string.Format("{0:yyyy-MM-dd}", CommonHelper.GetDateTime(keyJsonMap[key].ToString()));
                                keyJsonMap[key] = value;
                            }
                            break;
                        case "modifyUser":
                            {
                                keyJsonMap[key] = keyJsonMap[key];
                            }
                            break;
                        case "modifyTime":
                            {
                                string value = string.Format("{0:yyyy-MM-dd}", CommonHelper.GetDateTime(keyJsonMap[key].ToString()));
                                keyJsonMap[key] = value;
                            }
                            break;
                        case "cascader":
                            {
                                switch (configModel.dataType)
                                {
                                    case "dictionary":
                                        {
                                            List<DictionaryDataEntity> data = new List<DictionaryDataEntity>();
                                            if (redisHelper.Exists(CacheKey.VISUALDEV + configModel.dictionaryType))
                                            {
                                                data = redisHelper.Get(CacheKey.VISUALDEV + configModel.dictionaryType).ToObject<List<DictionaryDataEntity>>();
                                            }
                                            else
                                            {
                                                data = await dictionaryService.GetList(configModel.dictionaryType);
                                                redisHelper.Insert(CacheKey.VISUALDEV + configModel.dictionaryType, data);
                                                redisList.Add(CacheKey.VISUALDEV + configModel.dictionaryType);
                                            }
                                            List<string> dataList = keyJsonMap[key].ToObject<List<string>>();
                                            List<string> cascaderList = new List<string>();
                                            foreach (var items in dataList)
                                            {
                                                var cascader = data.Find(d => d.Id == items);
                                                if (cascader != null)
                                                {
                                                    cascaderList.Add(cascader.FullName);
                                                }
                                            }
                                            keyJsonMap[key] = cascaderList;
                                        }
                                        break;
                                    case "dynamic":
                                        {
                                            //获取远端数据
                                            //DataInterfaceEntity dynamic = await dataInterfaceService.GetInfo(configModel.propsUrl);
                                            //if (1.Equals(dynamic.DataType))
                                            //{
                                            //    var linkEntity = await dbLinkservice.GetInfo(dynamic.DBLinkId);
                                            //    var dt = await databaseService.GetInterFaceData(linkEntity, dynamic.Query);
                                            //    List<Dictionary<string, object>> dynamicDataList = UtilConvert.DataTableToDicList(dt);
                                            //    List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                            //    foreach (var item in dynamicDataList)
                                            //    {
                                            //        Dictionary<string, string> dynamicDic = new Dictionary<string, string>();
                                            //        dynamicDic.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                            //        list.Add(dynamicDic);
                                            //    }
                                            //    templateData.Add(fieldName1, list);
                                            //}
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            break;
                    }
                }
            }
            Dictionary<string, object> map = new Dictionary<string, object>();
            map[VMDEnumType.LIST.FindDescription()] = list;
            map[VMDEnumType.KEYJSONMAP.FindDescription()] = keyJsonMap;
            return map;
        }

        /// <summary>
        /// 将系统自动生成数据转换为数据
        /// </summary>
        /// <param name="formData">数据库模板数据</param>
        /// <param name="templateData">模板真实数据</param>
        /// <param name="entity">真实数据</param>
        /// <returns></returns>
        public async Task<string> GetAutomaticKeyData(List<FieldsModel> formData, Dictionary<string, object> templateData, string modelData)
        {
            //剔除无限极
            formData = TemplateDataConversion(formData);
            //数据库保存的F_Data
            Dictionary<string, object> dataMap = modelData.ToObject<Dictionary<string, object>>();
            int dicCount = dataMap.Keys.Count;
            string[] strKey = new string[dicCount];
            dataMap.Keys.CopyTo(strKey, 0);
            //自动生成的数据不在模板数据内
            var record = dataMap.Keys.Except(templateData.Keys).ToList();
            foreach (var key in record)
            {
                if (dataMap[key] != null)
                {
                    var dataValue = dataMap[key].ToString();
                    if (!string.IsNullOrEmpty(dataValue))
                    {
                        var model = formData.Where(f => f.__vModel__ == key).FirstOrDefault();
                        ConfigModel configModel = model.__config__;
                        string type = configModel.jnpfKey;
                        switch (type)
                        {
                            case "currDept":
                                {
                                    List<OrganizeEntity> orgMapList = await organizeService.GetList();
                                    foreach (var organizeEntity in orgMapList)
                                    {
                                        if (dataMap[key].ToString().Equals(organizeEntity.Id))
                                        {
                                            dataMap[key] = organizeEntity.FullName;
                                        }
                                    }
                                }
                                break;
                            case "createUser":
                                {
                                    UserEntity userCreEntity = await userService.GetInfo(dataMap[key].ToString());
                                    if (userCreEntity != null)
                                    {
                                        dataMap[key] = userCreEntity.RealName;
                                    }
                                }
                                break;
                            case "modifyUser":
                                {
                                    UserEntity userModEntity = await userService.GetInfo(dataMap[key].ToString());
                                    if (userModEntity != null)
                                    {
                                        dataMap[key] = userModEntity.RealName;
                                    }
                                }
                                break;
                            case "currPosition":
                                {
                                    List<PositionEntity> mapList = await positionService.GetList();
                                    var position = mapList.Where(p => p.Id == dataMap[key].ToString()).FirstOrDefault();
                                    if (position != null)
                                    {
                                        dataMap[key] = position.FullName;
                                    }
                                }
                                break;
                            case "currOrganize":
                                {
                                    List<OrganizeEntity> orgMapList = await organizeService.GetList();
                                    foreach (var organizeEntity in orgMapList)
                                    {
                                        if (dataMap[key].ToString().Equals(organizeEntity.Id))
                                        {
                                            dataMap[key] = organizeEntity.FullName;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
            }
            return SerializeHelper.SerializeToString(dataMap);
        }

        /// <summary>
        /// 获取单条信息时，主表将时间字符串转时间戳，子表将字符串类型的数组时间戳转成Json数组时间戳
        /// </summary>
        /// <param name="data"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<VisualDevModelDataInfoOutput> GetTableInfo(string id, VisualDevEntity visualdevEntity)
        {
            VisualDevModelDataInfoOutput output = new VisualDevModelDataInfoOutput();
            FormDataModel formData = TemplateKeywordsHelper.ReplaceKeywords(visualdevEntity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> modelList = formData.fields.ToList<FieldsModel>();
            modelList = TemplateDataConversion(modelList);
            List<TableModel> tableMapList = visualdevEntity.Tables.ToObject<List<TableModel>>();
            StringBuilder mainfeild = new StringBuilder();
            StringBuilder mainSql = new StringBuilder();
            var mainTable = tableMapList.Find(m => m.relationTable == "");
            var tableList = new List<DbTableFieldModel>();
            tableList = databaseService.GetFieldListByNoAsync(null, mainTable.table);
            var mainPrimary = tableList.Find(t => t.PrimaryKey == 1);
            mainSql.AppendFormat("select * from {0} where {2}='{1}';", mainTable.table, id, mainPrimary.Field);
            List<Dictionary<string, object>> mainMap = await GetTableDataInfoByTimeStamp(mainSql.ToString(), modelList, "query");
            //记录全部主表数据
            Dictionary<string, object> dataMap = mainMap.FirstOrDefault();
            Dictionary<string, object> newDataMap = new Dictionary<string, object>();
            foreach (var model in modelList)
            {
                if (!string.IsNullOrEmpty(model.__vModel__))
                {
                    if ("table".Equals(model.__config__.jnpfKey))
                    {
                        StringBuilder feilds = new StringBuilder();
                        List<FieldsModel> childModelList = model.__config__.children;
                        foreach (var childModel in childModelList)
                        {
                            feilds.Append(childModel.__vModel__ + ",");
                        }
                        if (childModelList.Count > 0)
                        {
                            feilds = new StringBuilder(feilds.ToString().TrimEnd(','));
                        }
                        //子表字段
                        string relationFeild = "";
                        //主表字段
                        string relationMainFeild = "";
                        string relationMainFeildValue = "";
                        //查询子表数据
                        StringBuilder childSql = new StringBuilder();
                        childSql.Append("select " + feilds + " from " + model.__config__.tableName + " where 1=1 ");
                        foreach (var tableMap in tableMapList)
                        {
                            if (tableMap.table.Equals(model.__config__.tableName))
                            {
                                relationFeild = tableMap.tableField;
                                relationMainFeild = tableMap.relationField;
                                if (dataMap.ContainsKey(relationMainFeild))
                                {
                                    relationMainFeildValue = dataMap[relationMainFeild].ToString();
                                    childSql.Append(@" And " + relationFeild + "='" + relationMainFeildValue + "'");
                                }
                                var childTableData = await GetTableDataInfoByTimeStamp(childSql.ToString(), model.__config__.children, "query");
                                if (childTableData.Count > 0)
                                {
                                    newDataMap[model.__vModel__] = childTableData;
                                }
                            }
                        }
                    }
                    else
                    {
                        mainfeild.Append(model.__vModel__ + ",");
                    }
                }
            }
            if (modelList.Count > 0)
            {
                mainfeild = new StringBuilder(mainfeild.ToString().TrimEnd(','));
            }
            int dicCount = newDataMap.Keys.Count;
            string[] strKey = new string[dicCount];
            newDataMap.Keys.CopyTo(strKey, 0);
            for (int i = 0; i < strKey.Length; i++)
            {
                var model = modelList.Where(m => m.__vModel__ == strKey[i]).FirstOrDefault();
                if (model != null)
                {
                    List<Dictionary<string, object>> tables = newDataMap[strKey[i]].ToObject<List<Dictionary<string, object>>>();
                    List<Dictionary<string, object>> newTables = new List<Dictionary<string, object>>();
                    foreach (var item in tables)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        foreach (var value in item)
                        {
                            var child = model.__config__.children.Find(c => c.__vModel__ == value.Key);
                            if (child != null)
                            {
                                dic.Add(value.Key, value.Value);
                                //ConfigModel configModel = child.__config__;
                                //string type = configModel.jnpfKey;
                                //switch (type)
                                //{
                                //    //日期选择
                                //    case JnpfKeyConsts.DATE:
                                //        {
                                //            if (value.Value != null)
                                //            {
                                //                long s = CommonHelper.TimeToTimeStamp(Convert.ToDateTime(value.Value.ToString()));
                                //                dic.Add(value.Key, s);
                                //            }
                                //        }
                                //        break;
                                //    default:
                                //        dic.Add(value.Key, value.Value);
                                //        break;
                                //}
                            }
                        }
                        newTables.Add(dic);
                    }
                    if (newTables.Count > 0)
                    {
                        newDataMap[strKey[i]] = newTables;
                    }
                }
            }
            foreach (var entryMap in dataMap)
            {
                if (entryMap.Value != null)
                {
                    var model = modelList.Where(m => m.__vModel__ == entryMap.Key.ToString()).FirstOrDefault();
                    if (model != null)
                    {
                        if (entryMap.Key.Equals(model.__vModel__))
                        {
                            if (mainfeild.ToString().Contains(entryMap.Key))
                            {
                                newDataMap[entryMap.Key] = entryMap.Value;
                            }
                        }
                    }
                }
            }
            string data = await autoFeilds(visualdevEntity.Id, modelList, SerializeHelper.SerializeToString(newDataMap));
            output.data = data;
            output.id = dataMap[mainPrimary.Field].ToString();
            return output;
        }

        /// <summary>
        /// 列表系统自动生成字段转换
        /// </summary>
        /// <param name="fieldsModelList"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<string> autoFeilds(string id, List<FieldsModel> modelList, string data)
        {
            //获取Redis缓存模板数据
            var templateData = await GetVisualDevTemplateData(id, modelList);
            data = await GetAutomaticKeyData(modelList, templateData, data);
            return data;
        }

        /// <summary>
        /// 列表系统自动生成字段转换
        /// </summary>
        /// <param name="fieldsModelList"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<string> autoFeilds(VisualDevEntity entity, string data)
        {
            FormDataModel formData = TemplateKeywordsHelper.ReplaceKeywords(entity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> modelList = formData.fields;
            //获取Redis缓存模板数据
            var templateData = await GetVisualDevTemplateData(entity.Id, modelList);
            data = await GetAutomaticKeyData(modelList, templateData, data);
            return data;
        }

        /// <summary>
        /// 获取有表单条数据
        /// </summary>
        /// <param name="main"></param>
        /// <returns></returns>
        public async Task<List<Dictionary<string, object>>> GetTableDataInfo(string main, List<FieldsModel> fieldsModels, string actionType)
        {
            using (var db = this.Basic)
            {
                List<Dictionary<string, object>> dataList = await db.GetPageDictionaryAsync(main);
                //转换表字符串成数组
                foreach (var dataMap in dataList)
                {
                    int dicCount = dataMap.Keys.Count;
                    string[] strKey = new string[dicCount];
                    dataMap.Keys.CopyTo(strKey, 0);
                    for (int i = 0; i < strKey.Length; i++)
                    {
                        var dataValue = dataMap[strKey[i]];
                        if (dataValue != null && !string.IsNullOrEmpty(dataValue.ToString()) && !dataValue.ToString().Contains("[]"))
                        {
                            var model = fieldsModels.Find(f => f.__vModel__ == strKey[i]);
                            if (model != null)
                            {
                                switch (model.__config__.jnpfKey)
                                {
                                    //日期选择
                                    case "date":
                                        {
                                            dataMap[strKey[i]] = TemplateControlsDataConversion(dataMap[strKey[i]], model, null);
                                        }
                                        break;
                                    default:
                                        dataMap[strKey[i]] = TemplateControlsDataConversion(dataMap[strKey[i]], model, actionType);
                                        break;
                                }

                            }
                        }
                    }
                }
                return dataList;
            }
        }

        /// <summary>
        /// 获取有表单条数据 转时间戳
        /// </summary>
        /// <param name="main"></param>
        /// <param name="fieldsModels"></param>
        /// <param name="actionType"></param>
        /// <returns></returns>
        public async Task<List<Dictionary<string, object>>> GetTableDataInfoByTimeStamp(string main, List<FieldsModel> fieldsModels, string actionType)
        {
            using (var db = this.Basic)
            {
                List<Dictionary<string, object>> dataList = await db.GetPageDictionaryAsync(main);
                //转换表字符串成数组
                foreach (var dataMap in dataList)
                {
                    int dicCount = dataMap.Keys.Count;
                    string[] strKey = new string[dicCount];
                    dataMap.Keys.CopyTo(strKey, 0);
                    for (int i = 0; i < strKey.Length; i++)
                    {
                        var dataValue = dataMap[strKey[i]];
                        if (dataValue != null && !string.IsNullOrEmpty(dataValue.ToString()) && !dataValue.ToString().Contains("[]"))
                        {
                            var model = fieldsModels.Find(f => f.__vModel__ == strKey[i]);
                            if (model != null)
                            {
                                dataMap[strKey[i]] = TemplateControlsDataConversion(dataMap[strKey[i]], model, actionType);
                            }
                        }
                    }
                }
                return dataList;
            }
        }

        public async Task<VisualDevModelDataEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<VisualDevModelDataEntity>(m => m.Id == id);
            }
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="visualdevEntity"></param>
        /// <returns></returns>
        public async Task<string> GetInfoDataChange(string id, VisualDevEntity visualdevEntity)
        {
            var entity = this.GetInfo(id);
            FormDataModel formData = TemplateKeywordsHelper.ReplaceKeywords(visualdevEntity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> modelList = formData.fields.ToList<FieldsModel>();
            modelList = TemplateDataConversion(modelList);
            //模板分离子表模板
            var childTemplateList = modelList.FindAll(m => m.__config__.jnpfKey == "table");
            //删除模板内子表模板
            modelList.RemoveAll(x => x.__config__.jnpfKey == "table");

            //获取真实数据
            var realData = entity.Result.Data.ToObject<Dictionary<string, object>>();
            //数据分离子表数据
            var childRealData = realData.Where(r => r.Key.StartsWith("tableField"));
            //获取关联表单
            var relationFormList = modelList.FindAll(m => m.__config__.jnpfKey == "relationForm");
            if (relationFormList.Count > 0)
            {
                foreach (var item in relationFormList)
                {
                    realData.Add(item.__vModel__ + "_id", null);
                }
            }


            //var childRealData = from d in realData where d.Key.StartsWith("tableField") select d;

            Dictionary<string, object> newDataMap = new Dictionary<string, object>();
            //循环子表数据
            foreach (var item in childRealData)
            {
                realData.Remove(item.Key);
                List<VisualDevModelDataEntity> childModelData = new List<VisualDevModelDataEntity>();
                var childTemplate = childTemplateList.Find(c => c.__vModel__ == item.Key);
                List<Dictionary<string, object>> tables = item.Value.ToObject<List<Dictionary<string, object>>>();
                List<Dictionary<string, object>> newTables = new List<Dictionary<string, object>>();
                if (childTemplate != null)
                {
                    foreach (var childColumn in tables)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        foreach (var column in childColumn)
                        {
                            var child = childTemplate.__config__.children.Find(c => c.__vModel__ == column.Key);
                            if (child != null)
                            {
                                dic.Add(column.Key, column.Value);
                            }
                        }
                        childModelData.Add(new VisualDevModelDataEntity()
                        {
                            Id = CommonHelper.Guid,
                            Data = dic.ToJson()
                        });
                    }
                    if (childModelData.Count > 0)
                    {
                        //获取模板数据缓存
                        Dictionary<string, object> childTemplateData = await GetVisualDevTemplateData(CommonHelper.Guid, childTemplate.__config__.children);
                        //将关键字查询传输的id转换成名称
                        Dictionary<string, object> childKeyAndList = await GetKeyData(childTemplate.__config__.children, childTemplateData, null, childModelData);

                        foreach (var items in childKeyAndList["list"].ToObject<List<VisualDevModelDataEntity>>())
                        {
                            newTables.Add(items.Data.ToObject<Dictionary<string, object>>());
                        }

                        newDataMap[item.Key] = newTables;
                    }
                }
            }
            var modelData = new VisualDevModelDataEntity()
            {
                Id = entity.Id.ToString(),
                Data = realData.ToJson()
            };
            List<VisualDevModelDataEntity> listEntity = new List<VisualDevModelDataEntity>();
            listEntity.Add(modelData);

            //获取模板数据缓存
            Dictionary<string, object> templateData = await GetVisualDevTemplateData(visualdevEntity.Id, modelList);
            //将关键字查询传输的id转换成名称
            Dictionary<string, object> keyAndList = await GetKeyData(modelList, templateData, null, listEntity);
            var convData = keyAndList["list"].ToObject<List<VisualDevModelDataEntity>>().FirstOrDefault().Data.ToObject<Dictionary<string, object>>();

            //foreach (var entryMap in convData)
            //{
            //    if (entryMap.Value != null)
            //    {
            //        var model = modelList.Where(m => m.__vModel__ == entryMap.Key.ToString()).FirstOrDefault();
            //        if (model != null)
            //        {
            //            newDataMap[entryMap.Key] = entryMap.Value;
            //        }
            //    }
            //}

            return convData.ToJson();
        }

        /// <summary>
        /// 获取详情带转换
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="visualdevEntity">模板数据</param>
        /// <returns></returns>
        public async Task<VisualDevModelDataInfoOutput> GetInfo(string id, VisualDevEntity visualdevEntity)
        {
            VisualDevModelDataInfoOutput output = new VisualDevModelDataInfoOutput();
            FormDataModel formData = TemplateKeywordsHelper.ReplaceKeywords(visualdevEntity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> modelList = formData.fields.ToList<FieldsModel>();
            modelList = TemplateDataConversion(modelList);
            List<TableModel> tableMapList = visualdevEntity.Tables.ToObject<List<TableModel>>();
            StringBuilder mainfeild = new StringBuilder();
            StringBuilder mainSql = new StringBuilder();
            var mainTable = tableMapList.Find(m => m.relationTable == "");
            var tableList = new List<DbTableFieldModel>();
            tableList = databaseService.GetFieldListByNoAsync(null, mainTable.table);
            var mainPrimary = tableList.Find(t => t.PrimaryKey == 1);
            mainSql.AppendFormat("select * from {0} where {2}='{1}';", mainTable.table, id, mainPrimary.Field);
            List<Dictionary<string, object>> mainMap = await GetTableDataInfo(mainSql.ToString(), modelList, null);
            //记录全部主表数据
            Dictionary<string, object> dataMap = mainMap.FirstOrDefault();
            Dictionary<string, object> newDataMap = new Dictionary<string, object>();
            foreach (var model in modelList)
            {
                if (!string.IsNullOrEmpty(model.__vModel__))
                {
                    if ("table".Equals(model.__config__.jnpfKey))
                    {
                        StringBuilder feilds = new StringBuilder();
                        List<FieldsModel> childModelList = model.__config__.children;
                        foreach (var childModel in childModelList)
                        {
                            feilds.Append(childModel.__vModel__ + ",");
                        }
                        if (childModelList.Count > 0)
                        {
                            feilds = new StringBuilder(feilds.ToString().TrimEnd(','));
                        }
                        //子表字段
                        string relationFeild = "";
                        //主表字段
                        string relationMainFeild = "";
                        string relationMainFeildValue = "";
                        //查询子表数据
                        StringBuilder childSql = new StringBuilder();
                        childSql.Append("select " + feilds + " from " + model.__config__.tableName + " where 1=1 ");
                        foreach (var tableMap in tableMapList)
                        {
                            if (tableMap.table.Equals(model.__config__.tableName))
                            {
                                relationFeild = tableMap.tableField;
                                relationMainFeild = tableMap.relationField;
                                if (dataMap.ContainsKey(relationMainFeild))
                                {
                                    relationMainFeildValue = dataMap[relationMainFeild].ToString();
                                    childSql.Append(@" And " + relationFeild + "='" + relationMainFeildValue + "'");
                                }
                                var childTableData = await GetTableDataInfo(childSql.ToString(), model.__config__.children, "query");
                                if (childTableData.Count > 0)
                                {
                                    newDataMap[model.__vModel__] = childTableData;
                                }
                            }
                        }
                    }
                    else
                    {
                        mainfeild.Append(model.__vModel__ + ",");
                    }
                }
            }
            if (modelList.Count > 0)
            {
                mainfeild = new StringBuilder(mainfeild.ToString().TrimEnd(','));
            }
            int dicCount = newDataMap.Keys.Count;
            string[] strKey = new string[dicCount];
            newDataMap.Keys.CopyTo(strKey, 0);
            for (int i = 0; i < strKey.Length; i++)
            {
                var model = modelList.Find(m => m.__vModel__ == strKey[i]);
                if (model != null)
                {
                    List<VisualDevModelDataEntity> childModelData = new List<VisualDevModelDataEntity>();
                    List<Dictionary<string, object>> tables = newDataMap[strKey[i]].ToObject<List<Dictionary<string, object>>>();
                    List<Dictionary<string, object>> newTables = new List<Dictionary<string, object>>();
                    foreach (var item in tables)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        foreach (var value in item)
                        {
                            var child = model.__config__.children.Find(c => c.__vModel__ == value.Key);
                            if (child != null && value.Value != null)
                            {
                                dic.Add(value.Key, value.Value);
                            }
                        }
                        childModelData.Add(new VisualDevModelDataEntity()
                        {
                            Id = CommonHelper.Guid,
                            Data = dic.ToJson()
                        });
                    }
                    if (childModelData.Count > 0)
                    {
                        //获取模板数据缓存
                        Dictionary<string, object> childTemplateData = await GetVisualDevTemplateData(CommonHelper.Guid, model.__config__.children);
                        //将关键字查询传输的id转换成名称
                        Dictionary<string, object> childKeyAndList = await GetKeyData(model.__config__.children, childTemplateData, null, childModelData);

                        foreach (var item in childKeyAndList["list"].ToObject<List<VisualDevModelDataEntity>>())
                        {
                            newTables.Add(item.Data.ToObject<Dictionary<string, object>>());
                        }

                        newDataMap[strKey[i]] = newTables;
                    }

                }
            }

            var entity = new VisualDevModelDataEntity()
            {
                Id = dataMap[mainPrimary.Field].ToString(),
                Data = dataMap.ToJson()
            };
            List<VisualDevModelDataEntity> listEntity = new List<VisualDevModelDataEntity>();
            listEntity.Add(entity);
            //获取模板数据缓存
            Dictionary<string, object> templateData = await GetVisualDevTemplateData(visualdevEntity.Id, modelList);
            //将关键字查询传输的id转换成名称
            Dictionary<string, object> keyAndList = await GetKeyData(modelList, templateData, null, listEntity);
            var convData = keyAndList["list"].ToObject<List<VisualDevModelDataEntity>>().FirstOrDefault().Data.ToObject<Dictionary<string, object>>();

            foreach (var entryMap in convData)
            {
                if (entryMap.Value != null)
                {
                    var model = modelList.Where(m => m.__vModel__ == entryMap.Key.ToString()).FirstOrDefault();
                    if (model != null)
                    {
                        if (entryMap.Key.Equals(model.__vModel__))
                        {
                            if (mainfeild.ToString().Contains(entryMap.Key))
                            {
                                newDataMap[entryMap.Key] = entryMap.Value;
                            }
                        }
                    }
                }
            }
            output.data = newDataMap.ToJson();
            output.id = dataMap[mainPrimary.Field].ToString();
            return output;
        }

        /// <summary>
        /// 主表添加时将时间转换成字符串时间，子表不做改变
        /// </summary>
        /// <param name="visualdevEntity"></param>
        /// <param name="visualdevModelDataCrForm"></param>
        /// <returns></returns>
        public async Task<int> Create(VisualDevEntity visualdevEntity, VisualDevModelDataCrForm visualdevModelDataCrForm)
        {
            Dictionary<string, object> allDataMap = visualdevModelDataCrForm.data.ToObject<Dictionary<string, object>>();
            var formData = TemplateKeywordsHelper.ReplaceKeywords(visualdevEntity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> fieldsModelList = formData.fields.ToObject<List<FieldsModel>>();
            //剔除布局控件
            fieldsModelList = TemplateDataConversion(fieldsModelList);
            //生成系统自动生成字段
            allDataMap = await generateFeilds(fieldsModelList, allDataMap, true);
            if (!string.IsNullOrEmpty(visualdevEntity.Tables) && !"[]".Equals(visualdevEntity.Tables))
            {
                string mainId = CommonHelper.Guid.ToString();
                //实例化模板信息
                List<TableModel> tableMapList = visualdevEntity.Tables.ToObject<List<TableModel>>();
                //获取主表
                var mainTable = tableMapList.Find(t => t.relationTable == "");
                var tableList = new List<DbTableFieldModel>();
                tableList = databaseService.GetFieldListByNoAsync(null, mainTable.table);
                //分离主子表数据
                //先记录子表数据
                var childTableDataKey = allDataMap.Where(d => d.Key.Contains("tableField")).Select(d => d.Key).ToList();
                //记录主表数据
                var mainPrimary = tableList.Find(t => t.PrimaryKey == 1);
                var mainTableDataKey = allDataMap.Keys.Except(childTableDataKey).ToList();
                ////主表字段集合
                StringBuilder mainFelid = new StringBuilder();
                List<string> mainFelidList = new List<string>();
                //主表查询语句
                StringBuilder mainSql = new StringBuilder();
                StringBuilder mainColumn = new StringBuilder();
                StringBuilder mainValues = new StringBuilder();
                //子表查询语句
                StringBuilder childSql = new StringBuilder();
                //拼接主表查询语句
                var mainFields = mainTable.fields;
                foreach (var item in mainTableDataKey)
                {
                    var mainField = mainFields.Where(f => f.Field == item).FirstOrDefault();
                    if (mainField != null)
                    {
                        var allMap = allDataMap[item];
                        if (allMap != null && !string.IsNullOrEmpty(allMap.ToString()))
                        {
                            //Column部分
                            mainColumn.AppendFormat("{0},", item);
                            //Values部分
                            mainValues.AppendFormat("'{0}',", TransformDataObject(allMap, item, fieldsModelList));
                            //mainValues.AppendFormat("{0},", allMap == null && string.IsNullOrEmpty(allMap.ToString()) ? "null" : "'" + GetObjectByTimestamp(allMap) + "'");
                        }
                    }
                }
                //去除多余的,
                if (mainTableDataKey.Count > 0)
                {
                    mainSql.AppendFormat("insert into {0} ({3},{1}) values('{4}',{2});", mainTable.table, mainColumn.ToString().Trim(','), mainValues.ToString().Trim(','), mainPrimary.Field, mainId);
                }
                //拼接子表sql
                foreach (var item in childTableDataKey)
                {
                    //查找到该控件数据
                    var model = allDataMap[item].ToJson().ToList<Dictionary<string, object>>();
                    if (model.Count > 0)
                    {
                        //利用key去找模板
                        var fieldsModel = fieldsModelList.Find(f => f.__vModel__ == item);
                        var fieldsConfig = fieldsModel.__config__;
                        model = GetTableDataListByDic(model, fieldsConfig.children);
                        StringBuilder childColumn = new StringBuilder();
                        StringBuilder childValues = new StringBuilder();
                        var childTable = tableMapList.Find(t => t.table == fieldsModel.__config__.tableName);
                        tableList = new List<DbTableFieldModel>();
                        tableList = databaseService.GetFieldListByNoAsync(null, childTable.table);
                        var childPrimary = tableList.Find(t => t.PrimaryKey == 1);
                        foreach (var data in model)
                        {
                            if (data.Count > 0)
                            {
                                foreach (KeyValuePair<string, object> child in data)
                                {
                                    if (child.Value != null)
                                    {
                                        //Column部分
                                        childColumn.AppendFormat("{0},", child.Key);
                                        //Values部分
                                        childValues.AppendFormat("'{0}',", TransformDataObject(child.Value, child.Key, fieldsConfig.children));
                                    }
                                }
                                if (!string.IsNullOrEmpty(childColumn.ToString()))
                                {
                                    childSql.AppendFormat("insert into {0}({6},{4},{1}) values('{3}','{5}',{2});", fieldsModel.__config__.tableName, childColumn.ToString().Trim(','), childValues.ToString().Trim(','), CommonHelper.Guid.ToString(), childTable.tableField, mainId, childPrimary.Field);
                                }
                                childColumn = new StringBuilder();
                                childValues = new StringBuilder();
                            }
                        }
                    }
                }
                return await opaTableDataInfo(mainSql.ToString() + childSql.ToString());
            }
            else
            {
                VisualDevModelDataEntity entity = new VisualDevModelDataEntity();
                entity.Data = SerializeHelper.SerializeToString(allDataMap);
                entity.VisualDevId = visualdevEntity.Id;
                entity.Id = CommonHelper.Guid.ToString();
                entity.SortCode = CommonHelper.SortCode;
                entity.CreatorTime = DateTime.Now;
                entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                entity.EnabledMark = 1;
                using (var db = this.Basic)
                {
                    return await db.InsertAsync(entity);
                }
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id">修改ID</param>
        /// <param name="visualdevEntity"></param>
        /// <param name="visualdevModelDataUpForm"></param>
        /// <returns></returns>
        public async Task<int> Update(string id, VisualDevEntity visualdevEntity, VisualDevModelDataCrForm visualdevModelDataUpForm)
        {
            Dictionary<string, object> allDataMap = visualdevModelDataUpForm.data.ToObject<Dictionary<string, object>>();
            FormDataModel formData = TemplateKeywordsHelper.ReplaceKeywords(visualdevEntity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> fieldsModelList = formData.fields.ToObject<List<FieldsModel>>();
            fieldsModelList = TemplateDataConversion(fieldsModelList);
            //生成系统自动生成字段
            allDataMap = await generateFeilds(fieldsModelList, allDataMap, false);
            Dictionary<string, object> newMainDataMap = visualdevModelDataUpForm.data.ToObject<Dictionary<string, object>>();
            if (!string.IsNullOrEmpty(visualdevEntity.Tables) && !"[]".Equals(visualdevEntity.Tables))
            {
                List<TableModel> tableMapList = visualdevEntity.Tables.ToObject<List<TableModel>>();
                //循环表
                var mainTable = tableMapList.Where(t => t.relationTable == "").FirstOrDefault();
                var tableList = new List<DbTableFieldModel>();
                tableList = databaseService.GetFieldListByNoAsync(null, mainTable.table);
                var mainPrimary = tableList.Find(t => t.PrimaryKey == 1);
                StringBuilder delMain = new StringBuilder();
                delMain.AppendFormat("delete from {0} where {2}='{1}';", mainTable.table, id, mainPrimary.Field);
                StringBuilder allDelSql = new StringBuilder();
                allDelSql.AppendFormat("{0}", delMain.ToString());
                StringBuilder queryMain = new StringBuilder();
                queryMain.AppendFormat("select * from {0} where {2}='{1}';", mainTable.table, id, mainPrimary.Field);
                Dictionary<string, object> mainMap = (await GetTableDataInfo(queryMain.ToString(), fieldsModelList, "query")).FirstOrDefault();
                if (tableMapList.Count > 1)
                {
                    //去除主表,剩余的为子表，再进行子表删除语句生成
                    tableMapList.RemoveAt(0);
                    foreach (var tableMap in tableMapList)
                    {
                        //主表字段
                        //与主表关联字段
                        string relationField = tableMap.relationField;
                        var relationFieldValue = mainMap.Where(f => f.Key == relationField).FirstOrDefault();
                        //子表字段
                        string tableField = tableMap.tableField;
                        allDelSql.AppendFormat("delete from {0} where {1}='{2}';", tableMap.table, tableField, relationFieldValue.Value);
                    }
                }

                string mainId = id;
                //分离主子表数据
                //先记录子表数据
                var childTableDataKey = allDataMap.Where(d => d.Key.Contains("tableField")).Select(d => d.Key).ToList();
                //记录主表数据
                var mainTableDataKey = allDataMap.Keys.Except(childTableDataKey).ToList();
                //实例化模板信息
                //主表字段集合
                StringBuilder mainFelid = new StringBuilder();
                List<string> mainFelidList = new List<string>();
                //主表查询语句
                StringBuilder mainSql = new StringBuilder();
                StringBuilder mainColumn = new StringBuilder();
                StringBuilder mainValues = new StringBuilder();
                //子表查询语句
                StringBuilder childSql = new StringBuilder();
                //拼接主表插入语句
                var mainFields = mainTable.fields;
                foreach (var item in mainTableDataKey)
                {
                    var mainField = mainFields.Where(f => f.Field == item).FirstOrDefault();
                    if (mainField != null)
                    {
                        var allMap = allDataMap[item];
                        if (allMap != null && !string.IsNullOrEmpty(allMap.ToString()) && !allMap.ToString().Contains("[]"))
                        {
                            //Column部分
                            mainColumn.AppendFormat("{0},", item);
                            //Values部分
                            mainValues.AppendFormat("'{0}',", TransformDataObject(allMap, item, fieldsModelList));
                            //mainValues.AppendFormat("{0},", allDataMap[item] == null && string.IsNullOrEmpty(allMap.ToString()) ? "null" : "'" + GetObjectByTimestamp(allMap) + "'");
                        }
                    }
                }
                //去除多余的,
                if (mainTableDataKey.Count > 0)
                {
                    mainSql.AppendFormat("insert into {0} ({3},{1}) values('{4}',{2});", mainTable.table, mainColumn.ToString().Trim(','), mainValues.ToString().Trim(','), mainPrimary.Field, mainId);
                }
                //拼接子表sql
                foreach (var item in childTableDataKey)
                {
                    //查找到该控件数据
                    var model = allDataMap[item].ToJson().ToList<Dictionary<string, object>>();
                    if (model.Count > 0)
                    {
                        //利用key去找模板
                        var fieldsModel = fieldsModelList.Find(f => f.__vModel__ == item);
                        var fieldsConfig = fieldsModel.__config__;
                        model = GetTableDataListByDic(model, fieldsConfig.children);
                        StringBuilder childColumn = new StringBuilder();
                        StringBuilder childValues = new StringBuilder();
                        var childTable = tableMapList.Where(t => t.table == fieldsConfig.tableName).FirstOrDefault();
                        tableList = new List<DbTableFieldModel>();
                        tableList = databaseService.GetFieldListByNoAsync(null, childTable.table);
                        var childPrimary = tableList.Find(t => t.PrimaryKey == 1);
                        foreach (var data in model)
                        {
                            if (data.Count > 0)
                            {
                                foreach (KeyValuePair<string, object> child in data)
                                {
                                    if (child.Value != null)
                                    {
                                        //Column部分
                                        childColumn.AppendFormat("{0},", child.Key);
                                        //Values部分
                                        childValues.AppendFormat("'{0}',", TransformDataObject(child.Value, child.Key, fieldsConfig.children));
                                    }
                                }
                                if (!string.IsNullOrEmpty(childColumn.ToString()))
                                {
                                    childSql.AppendFormat("insert into {0}({6},{4},{1}) values('{3}','{5}',{2});", fieldsModel.__config__.tableName, childColumn.ToString().Trim(','), childValues.ToString().Trim(','), CommonHelper.Guid.ToString(), childTable.tableField, mainId, childPrimary.Field);
                                }
                                childColumn = new StringBuilder();
                                childValues = new StringBuilder();
                            }
                        }
                    }
                }
                return await opaTableDataInfo(allDelSql.ToString() + mainSql.ToString() + childSql.ToString());
            }
            else
            {
                VisualDevModelDataEntity entity = new VisualDevModelDataEntity();
                entity.Data = SerializeHelper.SerializeToString(allDataMap);
                entity.VisualDevId = visualdevEntity.Id;
                entity.Id = id;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;
                using (var db = this.Basic)
                {
                    return await db.UpdateAsync(entity);
                }
            }
        }

        /// <summary>
        /// 生成系统自动生成字段
        /// </summary>
        /// <param name="fieldsModelList">模板数据</param>
        /// <param name="allDataMap">真实数据</param>
        /// <param name="IsCreate">创建与修改标识 true创建 false 修改</param>
        /// <returns></returns>
        private async Task<Dictionary<string, object>> generateFeilds(List<FieldsModel> fieldsModelList, Dictionary<string, object> allDataMap, bool IsCreate)
        {
            int dicCount = allDataMap.Keys.Count;
            string[] strKey = new string[dicCount];
            allDataMap.Keys.CopyTo(strKey, 0);
            for (int i = 0; i < strKey.Length; i++)
            {
                //根据KEY查找模板
                var model = fieldsModelList.Find(f => f.__vModel__ == strKey[i]);
                if (model != null)
                {
                    //如果模板jnpfKey为table为子表数据
                    if ("table".Equals(model.__config__.jnpfKey) && allDataMap[strKey[i]] != null)
                    {
                        List<FieldsModel> childFieldsModelList = model.__config__.children;
                        List<Dictionary<string, object>> childAllDataMapList = allDataMap[strKey[i]].ToJson().ToList<Dictionary<string, object>>();
                        List<Dictionary<string, object>> newChildAllDataMapList = new List<Dictionary<string, object>>();
                        foreach (var childmap in childAllDataMapList)
                        {
                            var newChildData = new Dictionary<string, object>();
                            foreach (KeyValuePair<string, object> item in childmap)
                            {
                                var childFieldsModel = childFieldsModelList.Where(c => c.__vModel__ == item.Key).FirstOrDefault();
                                if (childFieldsModel != null)
                                {
                                    var userInfo = UserProvider.Instance.Get();
                                    if (childFieldsModel.__vModel__.Equals(item.Key))
                                    {
                                        string jnpfKeyType = childFieldsModel.__config__.jnpfKey;
                                        switch (jnpfKeyType)
                                        {
                                            case "billRule":
                                                string billNumber = await billRuleService.GetNumber(childFieldsModel.__config__.rule);
                                                if (!"单据规则不存在".Equals(billNumber))
                                                {
                                                    newChildData[item.Key] = billNumber;
                                                }
                                                else
                                                {
                                                    newChildData[item.Key] = "";
                                                }
                                                break;
                                            case "createUser":
                                                if (IsCreate)
                                                {
                                                    newChildData[item.Key] = userInfo.UserId;
                                                }
                                                break;
                                            case "createTime":
                                                if (IsCreate)
                                                {
                                                    newChildData[item.Key] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                                                }
                                                break;
                                            case "modifyUser":
                                                if (!IsCreate)
                                                {
                                                    newChildData[item.Key] = userInfo.UserId;
                                                }
                                                break;
                                            case "modifyTime":
                                                if (!IsCreate)
                                                {
                                                    newChildData[item.Key] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                                                }
                                                break;
                                            case "currDept":
                                                OrganizeEntity organizeEntity = await organizeService.GetInfo(userInfo.OrganizeId);
                                                if (organizeEntity != null)
                                                {
                                                    newChildData[item.Key] = organizeEntity.Id;
                                                }
                                                else
                                                {
                                                    newChildData[item.Key] = "";
                                                }
                                                break;
                                            case "currPosition":
                                                UserEntity userEntity = await userService.GetInfo(userInfo.UserId);
                                                PositionEntity positionEntity = await positionService.GetInfo(userEntity.PositionId.Split(",")[0]);
                                                if (positionEntity != null)
                                                {
                                                    newChildData[item.Key] = positionEntity.Id;
                                                }
                                                else
                                                {
                                                    newChildData[item.Key] = "";
                                                }
                                                break;
                                            case "currOrganize":
                                                {
                                                    OrganizeEntity UserOrganizeEntity = await organizeService.GetInfo(userInfo.OrganizeId);
                                                    OrganizeEntity UserOrganize = await organizeService.GetInfo(UserOrganizeEntity.ParentId);
                                                    if (UserOrganize != null)
                                                    {
                                                        allDataMap[strKey[i]] = UserOrganize.Id;
                                                    }
                                                    else
                                                    {
                                                        allDataMap[strKey[i]] = "";
                                                    }
                                                }
                                                break;
                                            default:
                                                newChildData[item.Key] = childmap[item.Key];
                                                break;
                                        }
                                    }
                                }
                            }
                            newChildAllDataMapList.Add(newChildData);
                            allDataMap[strKey[i]] = newChildAllDataMapList;
                        }
                    }
                    else
                    {
                        var userInfo = UserProvider.Instance.Get();
                        if (model.__vModel__.Equals(strKey[i]))
                        {
                            string jnpfKeyType = model.__config__.jnpfKey;
                            switch (jnpfKeyType)
                            {
                                case "billRule":
                                    string billNumber = await billRuleService.GetNumber(model.__config__.rule);
                                    if (!"单据规则不存在".Equals(billNumber))
                                    {
                                        allDataMap[strKey[i]] = billNumber;
                                    }
                                    else
                                    {
                                        allDataMap[strKey[i]] = "";
                                    }
                                    break;
                                case "createUser":
                                    if (IsCreate)
                                    {
                                        allDataMap[strKey[i]] = userInfo.UserId;
                                    }
                                    break;
                                case "createTime":
                                    if (IsCreate)
                                    {
                                        allDataMap[strKey[i]] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                                    }
                                    break;
                                case "modifyUser":
                                    if (!IsCreate)
                                    {
                                        allDataMap[strKey[i]] = userInfo.UserId;
                                    }
                                    break;
                                case "modifyTime":
                                    if (!IsCreate)
                                    {
                                        allDataMap[strKey[i]] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                                    }
                                    break;
                                case "currDept":
                                    OrganizeEntity organizeEntity = await organizeService.GetInfo(userInfo.OrganizeId);
                                    if (organizeEntity != null)
                                    {
                                        allDataMap[strKey[i]] = organizeEntity.Id;
                                    }
                                    else
                                    {
                                        allDataMap[strKey[i]] = "";
                                    }
                                    break;
                                case "currPosition":
                                    UserEntity userEntity = await userService.GetInfo(userInfo.UserId);
                                    PositionEntity positionEntity = await positionService.GetInfo(userEntity.PositionId.Split(",")[0]);
                                    if (positionEntity != null)
                                    {
                                        allDataMap[strKey[i]] = positionEntity.Id;
                                    }
                                    else
                                    {
                                        allDataMap[strKey[i]] = "";
                                    }
                                    break;
                                case "currOrganize":
                                    {
                                        OrganizeEntity UserOrganizeEntity = await organizeService.GetInfo(userInfo.OrganizeId);
                                        OrganizeEntity UserOrganize = await organizeService.GetInfo(UserOrganizeEntity.ParentId);
                                        if (UserOrganize != null)
                                        {
                                            allDataMap[strKey[i]] = UserOrganize.Id;
                                        }
                                        else
                                        {
                                            allDataMap[strKey[i]] = "";
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            return allDataMap;
        }

        //增加删除修改有表单条数据
        public async Task<int> opaTableDataInfo(string sql)
        {
            using (var db = this.Basic)
            {
                return await db.ExecuteSqlAsync(sql);
            }
        }

        /// <summary>
        /// 有表删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> TableDelete(string id, VisualDevEntity entity)
        {
            List<TableModel> tableMapList = entity.Tables.ToObject<List<TableModel>>();
            //获取详情模板
            FormDataModel formDataModel = TemplateKeywordsHelper.ReplaceKeywords(entity.FormData).ToObject<FormDataModel>();
            List<FieldsModel> formData = formDataModel.fields;

            var tableList = new List<DbTableFieldModel>();
            //获取主表
            var mainTable = tableMapList.Find(t => t.relationTable == "");
            tableList = databaseService.GetFieldListByNoAsync(null, mainTable.table);
            //获取主键
            var mainPrimary = tableList.Find(t => t.PrimaryKey == 1);
            //拼接语句
            //主表删除语句
            StringBuilder delMain = new StringBuilder();
            //总删除语句
            StringBuilder allDelSql = new StringBuilder();
            //查询主表信息语句
            StringBuilder queryMain = new StringBuilder();
            //子表删除语句
            StringBuilder childSql = new StringBuilder();
            delMain.AppendFormat("delete from {0} where {1} = '{2}';", mainTable.table, mainPrimary.Field, id);
            allDelSql.Append(delMain);
            queryMain.AppendFormat("select * from {0} where {1}='{2}';", tableMapList[0].table, mainPrimary.Field, id);
            List<Dictionary<string, object>> mainMapList = await GetTableDataInfo(queryMain.ToString(), formData, null);
            if (mainMapList.Count > 0)
            {
                if (tableMapList.Count > 1)
                {
                    //去除主表
                    tableMapList.Remove(mainTable);
                    foreach (var tableMap in tableMapList)
                    {
                        //主表字段
                        string relationField = tableMap.relationField;
                        string relationFieldValue = mainMapList[0][relationField].ToString();
                        //子表字段
                        string tableField = tableMap.tableField;
                        childSql.AppendFormat("delete from {0} where {1} = '{2}';", tableMap.table, tableField, relationFieldValue);
                        allDelSql.Append(childSql);
                    }
                }
                return await opaTableDataInfo(allDelSql.ToString());
            }
            return 0;
        }

        public async Task<int> Delete(VisualDevModelDataEntity entity)
        {
            using (var db = this.Basic)
            {
                if (entity != null)
                {
                    return await db.DeleteAsync(entity);
                }
                return 0;
            }
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="input"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<PageResult<Dictionary<string, object>>> exportData(List<VisualDevModelDataEntity> list, VisualDevModelListQueryInput input, VisualDevEntity entity)
        {
            using (var db = this.Basic)
            {
                PageResult<Dictionary<string, object>> realList = new PageResult<Dictionary<string, object>>();
                realList = await this.GetListResult(entity, input);
                return realList;
            }
        }

        public List<VisualDevModelDataEntity> GetTableDataList(List<Dictionary<string, object>> dicList)
        {
            List<VisualDevModelDataEntity> list = new List<VisualDevModelDataEntity>();
            foreach (var dataMap in dicList)
            {
                VisualDevModelDataEntity entity = new VisualDevModelDataEntity();
                int dicCount = dataMap.Keys.Count;
                string[] strKey = new string[dicCount];
                dataMap.Keys.CopyTo(strKey, 0);
                //for (int i = 0; i < strKey.Length; i++)
                //{
                //    if (dataMap[strKey[i]] != null)
                //    {
                //        if (RegularHelper.Check(dataMap[strKey[i]].ToString(), RegularHelper.Type.时间戳))
                //        {
                //            dataMap[strKey[i]] = string.Format("{0:yyyy-MM-dd HH:mm}", CommonHelper.GetDateTime(dataMap[strKey[i]].ToString()));
                //        }
                //    }
                //}
                //需要将小写的转为大写
                entity.Data = SerializeHelper.SerializeToString(dataMap);
                entity.Id = dataMap[strKey[0]].ToString();
                list.Add(entity);
            }
            return list;
        }

        /// <summary>
        /// 转换字典列表内是否有时间戳
        /// </summary>
        /// <param name="dicList"></param>
        /// <returns></returns>
        public List<Dictionary<string, object>> GetTableDataListByDic(List<Dictionary<string, object>> dicList, List<FieldsModel> fieldsModels)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (var dataMap in dicList)
            {
                int dicCount = dataMap.Keys.Count;
                string[] strKey = new string[dicCount];
                dataMap.Keys.CopyTo(strKey, 0);
                for (int i = 0; i < strKey.Length; i++)
                {
                    var dataValue = dataMap[strKey[i]];
                    if (dataValue != null && !string.IsNullOrEmpty(dataValue.ToString()))
                    {
                        var model = fieldsModels.Find(f => f.__vModel__ == strKey[i]);
                        if (model != null)
                        {
                            dataMap[strKey[i]] = TemplateControlsDataConversion(dataMap[strKey[i]], model, "transition");
                        }
                    }
                }
                list.Add(dataMap);
            }
            return list;
        }

        /// <summary>
        /// 获取可视化开发模板数据
        /// </summary>
        /// <param name="moldelId">模型id</param>
        /// <param name="formData">模板数据结构</param>
        /// <returns></returns>
        public async Task<Dictionary<string, object>> GetVisualDevTemplateData(string moldelId, List<FieldsModel> formData)
        {
            Dictionary<string, object> templateData = new Dictionary<string, object>();
            if (redisHelper.Exists(CacheKey.VISUALDEV + moldelId))
            {
                templateData = redisHelper.Get(CacheKey.VISUALDEV + moldelId).ToObject<Dictionary<string, object>>();
            }
            else
            {
                foreach (var model in formData)
                {
                    if (model != null && model.__vModel__ != null)
                    {
                        ConfigModel configModel = model.__config__;
                        string fieldName1 = model.__vModel__;
                        string type = configModel.jnpfKey;
                        switch (type)
                        {
                            //单选框
                            case JnpfKeyConsts.RADIO:
                                {
                                    if (VMDEnumType.DICTIONARY.FindDescription() == configModel.dataType)
                                    {
                                        List<DictionaryDataEntity> dictionaryDataEntityList = string.IsNullOrEmpty(configModel.dictionaryType) ? null : await dictionaryService.GetList(configModel.dictionaryType);
                                        List<Dictionary<string, string>> dictionaryDataList = new List<Dictionary<string, string>>();
                                        foreach (var item in dictionaryDataEntityList)
                                        {
                                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                            dictionary.Add(item.Id, item.FullName);
                                            dictionaryDataList.Add(dictionary);
                                        }
                                        templateData.Add(fieldName1, dictionaryDataList);
                                    }
                                    if (VMDEnumType.STATIC.FindDescription() == configModel.dataType)
                                    {
                                        List<Dictionary<string, string>> optionList = model.__slot__.options.ToObject<List<Dictionary<string, string>>>();
                                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                        foreach (var item in optionList)
                                        {
                                            Dictionary<string, string> option = new Dictionary<string, string>();
                                            option.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                            list.Add(option);
                                        }
                                        templateData.Add(fieldName1, list);
                                    }
                                    if (VMDEnumType.DYNAMIC.FindDescription() == configModel.dataType)
                                    {
                                        //获取远端数据
                                        DataInterfaceEntity dynamic = await dataInterfaceService.GetInfo(model.__config__.propsUrl);
                                        if (1.Equals(dynamic.DataType))
                                        {
                                            var linkEntity = await dbLinkservice.GetInfo(dynamic.DBLinkId);
                                            var dt = await databaseService.GetInterFaceData(linkEntity, dynamic.Query);
                                            List<Dictionary<string, object>> dynamicDataList = UtilConvert.DataTableToDicList(dt);
                                            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                            foreach (var item in dynamicDataList)
                                            {
                                                Dictionary<string, string> dynamicDic = new Dictionary<string, string>();
                                                dynamicDic.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                                list.Add(dynamicDic);
                                            }
                                            templateData.Add(fieldName1, list);
                                        }
                                    }
                                }
                                break;
                            //下拉框
                            case JnpfKeyConsts.SELECT:
                                {
                                    if (VMDEnumType.DICTIONARY.FindDescription() == configModel.dataType)
                                    {
                                        List<DictionaryDataEntity> dictionaryDataEntityList = string.IsNullOrEmpty(configModel.dictionaryType) ? null : await dictionaryService.GetList(configModel.dictionaryType);
                                        List<Dictionary<string, string>> dictionaryDataList = new List<Dictionary<string, string>>();
                                        foreach (var item in dictionaryDataEntityList)
                                        {
                                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                            dictionary.Add(item.Id, item.FullName);
                                            dictionaryDataList.Add(dictionary);
                                        }
                                        templateData.Add(fieldName1, dictionaryDataList);
                                    }
                                    else if (VMDEnumType.STATIC.FindDescription() == configModel.dataType)
                                    {
                                        List<Dictionary<string, string>> optionList = model.__slot__.options.ToObject<List<Dictionary<string, string>>>();
                                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                        foreach (var item in optionList)
                                        {
                                            Dictionary<string, string> option = new Dictionary<string, string>();
                                            option.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                            list.Add(option);
                                        }
                                        templateData.Add(fieldName1, list);
                                    }
                                    else if (VMDEnumType.DYNAMIC.FindDescription() == configModel.dataType)
                                    {
                                        //获取远端数据
                                        DataInterfaceEntity dynamic = await dataInterfaceService.GetInfo(model.__config__.propsUrl);
                                        if (1.Equals(dynamic.DataType))
                                        {
                                            var linkEntity = await dbLinkservice.GetInfo(dynamic.DBLinkId);
                                            var dt = await databaseService.GetInterFaceData(linkEntity, dynamic.Query);
                                            List<Dictionary<string, object>> dynamicDataList = UtilConvert.DataTableToDicList(dt);
                                            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                            foreach (var item in dynamicDataList)
                                            {
                                                Dictionary<string, string> dynamicDic = new Dictionary<string, string>();
                                                dynamicDic.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                                list.Add(dynamicDic);
                                            }
                                            templateData.Add(fieldName1, list);
                                        }
                                    }
                                }
                                break;
                            //复选框
                            case JnpfKeyConsts.CHECKBOX:
                                {
                                    if (VMDEnumType.DICTIONARY.FindDescription() == configModel.dataType)
                                    {
                                        List<DictionaryDataEntity> dictionaryDataEntityList = string.IsNullOrEmpty(configModel.dictionaryType) ? null : await dictionaryService.GetList(configModel.dictionaryType);
                                        List<Dictionary<string, string>> dictionaryDataList = new List<Dictionary<string, string>>();
                                        foreach (var item in dictionaryDataEntityList)
                                        {
                                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                            dictionary.Add(item.Id, item.FullName);
                                            dictionaryDataList.Add(dictionary);
                                        }
                                        templateData.Add(fieldName1, dictionaryDataList);
                                    }
                                    if (VMDEnumType.STATIC.FindDescription() == configModel.dataType)
                                    {
                                        List<Dictionary<string, string>> optionList = model.__slot__.options.ToObject<List<Dictionary<string, string>>>();
                                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                        foreach (var item in optionList)
                                        {
                                            Dictionary<string, string> option = new Dictionary<string, string>();
                                            option.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                            list.Add(option);
                                        }
                                        templateData.Add(fieldName1, list);
                                    }
                                    if (VMDEnumType.DYNAMIC.FindDescription() == configModel.dataType)
                                    {
                                        //获取远端数据
                                        DataInterfaceEntity dynamic = await dataInterfaceService.GetInfo(model.__config__.propsUrl);
                                        if (1.Equals(dynamic.DataType))
                                        {
                                            var linkEntity = await dbLinkservice.GetInfo(dynamic.DBLinkId);
                                            var dt = await databaseService.GetInterFaceData(linkEntity, dynamic.Query);
                                            List<Dictionary<string, object>> dynamicDataList = UtilConvert.DataTableToDicList(dt);
                                            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                            foreach (var item in dynamicDataList)
                                            {
                                                Dictionary<string, string> dynamicDic = new Dictionary<string, string>();
                                                dynamicDic.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                                list.Add(dynamicDic);
                                            }
                                            templateData.Add(fieldName1, list);
                                        }
                                    }
                                }
                                break;
                            //公司
                            case JnpfKeyConsts.COMSELECT:
                                {
                                    List<OrganizeEntity> com_organizeEntityList = await organizeService.GetList();
                                    List<Dictionary<string, string>> com_organizeList = new List<Dictionary<string, string>>();
                                    foreach (var item in com_organizeEntityList)
                                    {
                                        Dictionary<string, string> com_organize = new Dictionary<string, string>();
                                        com_organize.Add(item.Id, item.FullName);
                                        com_organizeList.Add(com_organize);
                                    }
                                    templateData.Add(fieldName1, com_organizeList);
                                }
                                break;
                            //部门
                            case JnpfKeyConsts.DEPSELECT:
                                {
                                    List<OrganizeEntity> dep_organizeEntityList = await organizeService.GetList();
                                    List<Dictionary<string, string>> dep_organizeList = new List<Dictionary<string, string>>();
                                    foreach (var item in dep_organizeEntityList)
                                    {
                                        Dictionary<string, string> dep_organize = new Dictionary<string, string>();
                                        dep_organize.Add(item.Id, item.FullName);
                                        dep_organizeList.Add(dep_organize);
                                    }
                                    templateData.Add(fieldName1, dep_organizeList);
                                }
                                break;
                            //岗位
                            case JnpfKeyConsts.POSSELECT:
                                {
                                    List<PositionEntity> positionEntityList = await positionService.GetList();
                                    List<Dictionary<string, string>> positionList = new List<Dictionary<string, string>>();
                                    foreach (var item in positionEntityList)
                                    {
                                        Dictionary<string, string> position = new Dictionary<string, string>();
                                        position.Add(item.Id, item.FullName);
                                        positionList.Add(position);
                                    }
                                    templateData.Add(fieldName1, positionList);
                                }
                                break;
                            //用户
                            case JnpfKeyConsts.USERSELECT:
                                {
                                    List<UserEntity> userEntityList = await userService.GetList();
                                    List<Dictionary<string, string>> userList = new List<Dictionary<string, string>>();
                                    foreach (var item in userEntityList)
                                    {
                                        Dictionary<string, string> user = new Dictionary<string, string>();
                                        user.Add(item.Id, item.RealName + "/" + item.Account);
                                        userList.Add(user);
                                    }
                                    templateData.Add(fieldName1, userList);
                                }
                                break;
                            //数据字典
                            case JnpfKeyConsts.DICTIONARY:
                                {
                                    List<DictionaryTypeEntity> dictionaryTypeEntityLists = await dictionaryTypeService.GetList();
                                    List<Dictionary<string, string>> dictionaryTypeList = new List<Dictionary<string, string>>();
                                    foreach (var item in dictionaryTypeEntityLists)
                                    {
                                        Dictionary<string, string> dictionaryType = new Dictionary<string, string>();
                                        dictionaryType.Add(item.Id, item.FullName);
                                        dictionaryTypeList.Add(dictionaryType);
                                    }
                                    templateData.Add(fieldName1, dictionaryTypeList);
                                }
                                break;
                            //省市区
                            case JnpfKeyConsts.ADDRESS:
                                {
                                    List<ProvinceEntity> addressEntityList = await provinceService.GetList();
                                    List<Dictionary<string, string>> addressList = new List<Dictionary<string, string>>();
                                    foreach (var item in addressEntityList)
                                    {
                                        Dictionary<string, string> address = new Dictionary<string, string>();
                                        address.Add(item.Id, item.FullName);
                                        addressList.Add(address);
                                    }
                                    templateData.Add(fieldName1, addressList);
                                }
                                break;
                            //级联选择
                            case JnpfKeyConsts.CASCADER:
                                {
                                    if (VMDEnumType.STATIC.FindDescription() == configModel.dataType)
                                    {
                                        var props = model.props.props;
                                        var optionList = GetTreeOptions(model.options, props);
                                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                        foreach (var item in optionList)
                                        {
                                            Dictionary<string, string> option = new Dictionary<string, string>();
                                            option.Add(item.value, item.label);
                                            list.Add(option);
                                        }
                                        templateData.Add(fieldName1, list);
                                    }
                                }
                                break;
                            //树形选择
                            case JnpfKeyConsts.TREESELECT:
                                {
                                    if (VMDEnumType.DICTIONARY.FindDescription() == configModel.dataType)
                                    {
                                        List<DictionaryDataEntity> dictionaryDataEntityList = await dictionaryService.GetList();
                                        List<Dictionary<string, string>> dictionaryDataList = new List<Dictionary<string, string>>();
                                        foreach (var item in dictionaryDataEntityList)
                                        {
                                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                            dictionary.Add(item.Id, item.FullName);
                                            dictionaryDataList.Add(dictionary);
                                        }
                                        templateData.Add(fieldName1, dictionaryDataList);
                                    }
                                    else if (VMDEnumType.STATIC.FindDescription() == configModel.dataType)
                                    {
                                        var props = model.props.props;
                                        var optionList = GetTreeOptions(model.options, props);
                                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                        foreach (var item in optionList)
                                        {
                                            Dictionary<string, string> option = new Dictionary<string, string>();
                                            option.Add(item.value, item.label);
                                            list.Add(option);
                                        }
                                        templateData.Add(fieldName1, list);
                                    }
                                    else if (VMDEnumType.DYNAMIC.FindDescription() == configModel.dataType)
                                    {
                                        //获取远端数据
                                        DataInterfaceEntity dynamic = await dataInterfaceService.GetInfo(model.__config__.propsUrl);
                                        if (1.Equals(dynamic.DataType))
                                        {
                                            var linkEntity = await dbLinkservice.GetInfo(dynamic.DBLinkId);
                                            var dt = await databaseService.GetInterFaceData(linkEntity, dynamic.Query);
                                            List<Dictionary<string, object>> dynamicDataList = UtilConvert.DataTableToDicList(dt);
                                            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                                            foreach (var item in dynamicDataList)
                                            {
                                                Dictionary<string, string> dynamicDic = new Dictionary<string, string>();
                                                dynamicDic.Add(item[model.__config__.props.value].ToString(), item[model.__config__.props.label].ToString());
                                                list.Add(dynamicDic);
                                            }
                                            templateData.Add(fieldName1, list);
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
                redisHelper.Insert(CacheKey.VISUALDEV + moldelId, templateData);
            }
            return templateData;
        }

        /// <summary>
        /// options无限级
        /// </summary>
        /// <returns></returns>
        public List<OptionsModel> GetTreeOptions(List<object> model, PropsBeanModel props)
        {
            List<OptionsModel> options = new List<OptionsModel>();
            foreach (var item in model)
            {
                OptionsModel option = new OptionsModel();
                var dicObject = item.ToObject<Dictionary<string, object>>();
                option.label = dicObject[props.label].ToString();
                option.value = dicObject[props.value].ToString();
                if (dicObject.ContainsKey(props.children))
                {
                    var children = dicObject[props.children].ToObject<List<object>>();
                    options.AddRange(GetTreeOptions(children, props));
                }
                options.Add(option);
            }
            return options;
        }

        /// <summary>
        /// 模板数据转换
        /// </summary>
        /// <param name="fieldsModelList"></param>
        /// <returns></returns>
        public List<FieldsModel> TemplateDataConversion(List<FieldsModel> fieldsModelList)
        {
            var template = new List<FieldsModel>();
            //将模板内的无线children解析出来
            foreach (var item in fieldsModelList)
            {
                var config = item.__config__;
                switch (config.jnpfKey)
                {
                    //栅格布局
                    case "row":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children));
                        }
                        break;
                    //表格
                    case "table":
                        {
                            template.Add(item);
                        }
                        break;
                    //卡片
                    case "card":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children));
                        }
                        break;
                    //文本
                    case "JNPFText":
                        break;
                    //分割线
                    case "divider":
                        break;
                    //分组标题
                    case "groupTitle":
                        break;
                    default:
                        {
                            template.Add(item);
                        }
                        break;
                }
            }
            return template;
        }

        /// <summary>
        /// 模板子集数据转换
        /// </summary>
        /// <param name="childrenList"></param>
        /// <returns></returns>
        public List<FieldsModel> TemplateChildrenDataConversion(List<FieldsModel> childrenList)
        {
            var template = new List<FieldsModel>();
            //将模板内的无线children解析出来
            foreach (var item in childrenList)
            {
                var config = item.__config__;
                switch (config.jnpfKey)
                {
                    //栅格布局
                    case "row":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children));
                        }
                        break;
                    //表格
                    case "table":
                        {
                            template.Add(item);
                        }
                        break;
                    //卡片
                    case "card":
                        {
                            template.AddRange(TemplateChildrenDataConversion(config.children));
                        }
                        break;
                    //文本
                    case "JNPFText":
                        break;
                    //分割线
                    case "divider":
                        break;
                    //分组标题
                    case "groupTitle":
                        break;
                    default:
                        {
                            template.Add(item);
                        }
                        break;
                }
            }
            return template;
        }

        /// <summary>
        /// 控制模板数据转换
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="fieldsModel">数据模板</param>
        /// <param name="actionType">操作类型(add-新增、query-查询、transition-过渡)</param>
        /// <returns></returns>
        public object TemplateControlsDataConversion(object data, FieldsModel fieldsModel, string actionType = null)
        {
            object conversionData = new object();
            switch (fieldsModel.__config__.jnpfKey)
            {
                //单行输入
                case "comInput":
                    {
                        conversionData = string.IsNullOrEmpty(data.ToString()) ? null : data.ToString();
                    }
                    break;
                //多行输入
                case "textarea":
                    {
                        conversionData = data.ToString();
                    }
                    break;
                //数字输入
                case "numInputc":
                    {
                        conversionData = data.ToInt();
                    }
                    break;
                //金额输入
                case "JNPFAmount":
                    {
                        conversionData = data.ToDecimal();
                    }
                    break;
                //单选框组
                case "radio":
                    {
                        conversionData = string.IsNullOrEmpty(data.ToString()) ? null : data.ToString();
                    }
                    break;
                //多选框组
                case "checkbox":
                    {
                        if (data.ToString() != "[]")
                        {
                            conversionData = data.ToString().ToObject<List<string>>();
                        }
                        else
                        {
                            conversionData = null;
                        }

                    }
                    break;
                //下拉选择
                case "select":
                    {
                        if (fieldsModel.multiple)
                        {
                            conversionData = data.ToObject<List<string>>();
                        }
                        else
                        {
                            conversionData = data.ToString();
                        }
                    }
                    break;
                //时间选择
                case "time":
                    {
                        switch (actionType)
                        {
                            case "query":
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", data);
                                break;
                            case "add":
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", data);
                                break;
                            case "transition":
                                conversionData = data.ToString();
                                break;
                            default:
                                conversionData = CommonHelper.TimeToTimeStamp(Convert.ToDateTime(data));
                                break;
                        }
                    }
                    break;
                //时间范围
                case "timeRange":
                    {
                        switch (actionType)
                        {
                            case "query":
                                conversionData = data.ToString().Replace("\"", "").Split(',').ToList<string>();
                                break;
                            case "transition":
                                conversionData = data.ToObject<List<string>>();
                                break;
                            default:
                                var list = data.ToObject<List<string>>();
                                conversionData = string.Join(',', list.ToList());
                                break;
                        }

                    }
                    break;
                //日期选择
                case "date":
                    {
                        switch (actionType)
                        {
                            case "query":
                                conversionData = CommonHelper.TimeToTimeStamp(Convert.ToDateTime(data));
                                break;
                            case "add":
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", CommonHelper.GetDateTime(data.ToString()));
                                break;
                            case "transition":
                                conversionData = (long)data;
                                break;
                            default:
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", Convert.ToDateTime(data));
                                break;
                        }
                    }
                    break;
                //日期范围
                case "dateRange":
                    {
                        switch (actionType)
                        {
                            case "query":
                                conversionData = data.ToString().Replace("\"", "").Split(',').ToList<string>();
                                break;
                            case "transition":
                                conversionData = data.ToObject<List<string>>();
                                break;
                            default:
                                var list = data.ToObject<List<string>>();
                                conversionData = string.Join(',', list.ToList());
                                break;
                        }
                    }
                    break;
                //创建时间
                case "createTime":
                    {
                        switch (actionType)
                        {
                            case "query":
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", data);
                                break;
                            case "add":
                                conversionData = data.ToString();
                                break;
                            //case "transition":
                            //    conversionData = CommonHelper.TimeToTimeStamp(Convert.ToDateTime(data));
                            //    break;
                            default:
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", data);
                                break;
                        }
                    }
                    break;
                //修改时间
                case "modifyTime":
                    {
                        switch (actionType)
                        {
                            case "query":
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", data);
                                break;
                            case "add":
                                conversionData = data.ToString();
                                break;
                            //case "transition":
                            //    conversionData = CommonHelper.TimeToTimeStamp(Convert.ToDateTime(data));
                            //    break;
                            default:
                                conversionData = string.Format("{0:yyyy-MM-dd HH:mm:ss}", data);
                                break;
                        }
                    }
                    break;
                //文件上传
                case "uploadFz":
                    {
                        if (data.ToString() != "[]")
                        {
                            conversionData = data.ToString().ToObject<List<FileControlsModel>>();
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //图片上传
                case "uploadImg":
                    {
                        if (data.ToString() != "[]")
                        {
                            conversionData = data.ToString().ToObject<List<FileControlsModel>>();
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //颜色选择
                case "colorPicker":
                    {
                        conversionData = string.IsNullOrEmpty(data.ToString()) ? null : data.ToString();
                    }
                    break;
                //评分
                case "rate":
                    {
                        conversionData = data.ToInt();
                    }
                    break;
                //开关
                case "switch":
                    {
                        conversionData = data.ToInt();
                    }
                    break;
                //滑块
                case "slider":
                    {
                        if (fieldsModel.range)
                        {
                            conversionData = data.ToString().ToObject<List<int>>();
                        }
                        else
                        {
                            conversionData = data.ToInt();
                        };
                    }
                    break;
                ////文本
                //case "JNPFText":
                //    break;
                //富文本
                case "editor":
                    {
                        conversionData = string.IsNullOrEmpty(data.ToString()) ? null : data.ToString();
                    }
                    break;
                //公司组件
                case "comSelect":
                    {
                        if (!string.IsNullOrEmpty(data.ToString()))
                        {
                            if (fieldsModel.multiple)
                            {
                                conversionData = data.ToString().Split(',').ToList<string>();
                            }
                            else
                            {
                                conversionData = data.ToString();
                            }
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //部门组件
                case "depSelect":
                    {
                        if (!string.IsNullOrEmpty(data.ToString()))
                        {
                            if (fieldsModel.multiple)
                            {
                                conversionData = data.ToString().Split(',').ToList<string>();
                            }
                            else
                            {
                                conversionData = data.ToString();
                            }
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //岗位组件
                case "posSelect":
                    {
                        if (!string.IsNullOrEmpty(data.ToString()))
                        {
                            if (fieldsModel.multiple)
                            {
                                conversionData = data.ToString().Split(',').ToList<string>();
                            }
                            else
                            {
                                conversionData = data.ToString();
                            }
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //用户组件
                case "userSelect":
                    {
                        if (!string.IsNullOrEmpty(data.ToString()))
                        {
                            if (fieldsModel.multiple)
                            {
                                conversionData = data.ToString().Split(',').ToList<string>();
                            }
                            else
                            {
                                conversionData = data.ToString();
                            }
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //树形选择
                case "treeSelect":
                    {
                        if (!string.IsNullOrEmpty(data.ToString()))
                        {
                            if (fieldsModel.multiple)
                            {
                                conversionData = data.ToString().Split(',').ToList<string>();
                            }
                            else
                            {
                                conversionData = data.ToString();
                            }
                        }
                        else
                        {
                            conversionData = null;
                        }
                    }
                    break;
                //单据组件
                case "billRule":
                    {
                        conversionData = data.ToString();
                    }
                    break;
                //省市区联动
                case "address":
                    {
                        conversionData = data.ToString().ToObject<List<string>>();
                    }
                    break;
                ////关联表单
                //case "relationForm":
                //    {
                //    }
                //    break;
                //关联表单属性
                //case "relationFormAttr":
                //    {
                //    }
                //    break;
                //创建人员
                case "createUser":
                    {
                        conversionData = data.ToString();
                    }
                    break;
                //修改人员
                case "modifyUser":
                    {
                        conversionData = string.IsNullOrEmpty(data.ToString()) ? null : data.ToString();
                    }
                    break;
                //所属公司
                case "currOrganize":
                    {
                        conversionData = data.ToString();
                    }
                    break;
                //所属部门
                case "currDept":
                    {
                        conversionData = data.ToString();
                    }
                    break;
                //所属岗位
                case "currPosition":
                    {
                        conversionData = data.ToString();
                    }
                    break;
                case "table":
                    {

                    }
                    break;
                //级联
                case "cascader":
                    conversionData = data.ToString().ToObject<List<string>>();
                    break;
                default:
                    conversionData = data.ToString();
                    break;
            }
            return conversionData;
        }

        /// <summary>
        /// 转换对应数据Object
        /// </summary>
        /// <param name="dataValue">数据值</param>
        /// <param name="dataKey">数据Key</param>
        /// <param name="fieldsModelList">模板</param>
        /// <returns></returns>
        public string TransformDataObject(object dataValue, string dataKey, List<FieldsModel> fieldsModelList)
        {
            StringBuilder sb = new StringBuilder();
            //根据KEY查找模板
            var model = fieldsModelList.Find(f => f.__vModel__ == dataKey);
            if (model != null)
            {
                switch (model.__config__.jnpfKey)
                {
                    //文件上传
                    case "uploadFz":
                        {
                            var fileList = TemplateControlsDataConversion(dataValue, model);
                            if (fileList != null)
                            {
                                sb.AppendFormat("{0}", JsonHelper.ToJson(fileList).Replace("{", "{{").Replace("}", "}}"));
                            }
                        }
                        break;
                    //图片上传
                    case "uploadImg":
                        {
                            var fileList = TemplateControlsDataConversion(dataValue, model);
                            if (fileList != null)
                            {
                                sb.AppendFormat("{0}", fileList.ToJson().Replace("{", "{{").Replace("}", "}}"));
                            }
                        }
                        break;
                    //省市区联动
                    case "address":
                        {
                            sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                        }
                        break;
                    //树形选择
                    case "treeSelect":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    //公司组件
                    case "comSelect":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    //部门组件
                    case "depSelect":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    //岗位组件
                    case "posSelect":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    //用户组件
                    case "userSelect":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    //滑块
                    case "slider":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    //时间范围
                    case "timeRange":
                        {
                            sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                        }
                        break;
                    //日期范围
                    case "dateRange":
                        {
                            sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                        }
                        break;
                    //下拉选择
                    case "select":
                        {
                            if (model.multiple)
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model).ToJson());
                            }
                            else
                            {
                                sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model));
                            }
                        }
                        break;
                    default:
                        sb.AppendFormat("{0}", TemplateControlsDataConversion(dataValue, model, "add"));
                        break;
                }
            }
            if (dataKey == "F_Id")
            {
                sb.AppendFormat("{0}", dataValue.ToString());
            }
            return sb.ToString();
        }
    }
}
